Structures and Unions in C

When one value cannot describe a thing, such as a sensor reading with an ID, a count and a measurement, C lets you bundle several typed fields into one user-defined type. A structure gives every field its own storage, while a union makes the fields share one block of storage. Knowing how the compiler lays out both lets you predict sizeof, read binary file formats and save memory in large arrays.

Declaring and using a structure

A structure is a user-defined type made of named members, each with its own type and its own storage, placed in memory in the order you declare them.


C
struct rec {
    char   tag;
    int    n;
    double x;
};

struct rec r = { 'a', 3, 2.5 };
r.n = 4;    /* the dot selects a member of a struct object */


The name rec is the structure tag, so the type is spelled struct rec. Through a pointer p to a structure, p->x is shorthand for (*p).x. Assigning one structure to another of the same type copies every member, but the equality operator does not work on whole structures, so compare members one at a time.

Memory layout: alignment and padding

Every type has an alignment requirement, and the compiler lays out members with three rules:

  1. The first member sits at offset 0, and later members follow in declaration order.
  2. Each member starts at the next offset that is a multiple of its alignment; the skipped bytes are padding.
  3. The total size is rounded up to a multiple of the largest member alignment, so every element of an array of the structure is also aligned.

With end=offset+size\text{end} = \text{offset} + \text{size} for each member:


offsetk=ak⌈endk−1ak⌉,sizeof=amax⁡⌈endlastamax⁡⌉\text{offset}_k = a_k \left\lceil \frac{\text{end}_{k-1}}{a_k} \right\rceil, \qquad \text{sizeof} = a_{\max} \left\lceil \frac{\text{end}_{\text{last}}}{a_{\max}} \right\rceil



Example: In struct rec, tag occupies byte 0. n needs an offset that is a multiple of 4, so bytes 1 to 3 become padding and n takes bytes 4 to 7. x needs a multiple of 8, and offset 8 is free, so it takes bytes 8 to 15. The end, 16, is already a multiple of 8, so sizeof(struct rec) is 16 rather than the 13 bytes the members need.


Member

Size (bytes)

Alignment

Offset

Bytes used

tag

1

1

0

0

padding

3

none

1

1 to 3

n

4

4

4

4 to 7

x

8

8

8

8 to 15


Two byte maps, one showing struct rec spread over 16 bytes with padding after tag and one showing the members of union rec_u stacked from byte 0 within 8 bytes.


You can check any offset in code with offsetof, for example offsetof(struct rec, x), which gives 8 here. Declaring members from largest alignment to smallest usually reduces padding, which matters when you store thousands of elements.

Unions: members that share storage

A union is declared like a structure, but all of its members start at offset 0 and overlap, so it holds only one member's value at a time.


C
union rec_u {
    char   tag;
    int    n;
    double x;
};


The size of a union is the size of its largest member, rounded up to a multiple of the strictest member alignment. For union rec_u the largest member is x at 8 bytes, already a multiple of 8, so sizeof(union rec_u) is 8.


Writing a member overwrites the bytes the other members share. Only the member stored most recently holds a meaningful value; reading a different member reinterprets the same bytes as another type, and the result depends on how the platform represents values. Programs usually pair a union with a separate field that records which member is active, a pattern called a tagged union.



Property

Structure

Union

Member offsets

Increasing, in declaration order

All 0

Size

Sum of member sizes plus padding

Largest member, rounded up to the strictest alignment

Values held at once

All members

One member

Typical use

A record with several fields

One of several alternative types


What to remember

  • A structure gives each member its own storage in declaration order; a union overlaps all members at offset 0.
  • Each member starts at a multiple of its alignment, and the gaps are padding.
  • A structure's size rounds up to a multiple of its largest member alignment, so arrays stay aligned.
  • A union's size is its largest member, rounded up to its strictest alignment.
  • Read back only the union member you stored last.

Example: Laying out a packet record

A network monitor stores each captured packet in the structure below. Assume the 64-bit platform used throughout: char, short and double occupy 1, 2 and 8 bytes and are each aligned to their own size.


C
struct packet {
    char   flag;
    double time;
    short  port;
};


a) Find the offset of each member and sizeof(struct packet).


flag is the first member, so it sits at offset 0 and ends at offset 1.


time needs an offset that is a multiple of 8. The next free offset is 1, so the compiler inserts ________ of padding and places time at offset 8. It ends at offset 16.


port needs a multiple of 2, and 16 qualifies, so port sits at offset 16 and the members end at offset ________.


The largest member alignment is 8, so the size rounds 18 up to the next multiple of 8:


sizeof=8⌈188⌉=8×3=24 bytes\text{sizeof} = 8 \left\lceil \frac{18}{8} \right\rceil = 8 \times 3 = 24\ \text{bytes}


The 6 bytes from offset 18 to 23 are trailing padding: they belong to the structure but hold no member. The offsets are 0, 8 and 16, and sizeof(struct packet) is 24 bytes, of which 11 hold data and 13 are padding.


b) Reorder the members to make the structure as small as possible and give its new size.


Declare the members from largest alignment to smallest: time, then port, then flag.


time takes offsets 0 to 7. port needs a multiple of 2 and takes offsets 8 and 9. flag takes offset 10, so the members end at offset ________.


Rounding up to a multiple of 8 adds ________ of trailing padding:


sizeof=8⌈118⌉=8×2=16 bytes\text{sizeof} = 8 \left\lceil \frac{11}{8} \right\rceil = 8 \times 2 = 16\ \text{bytes}


The reordered structure is 16 bytes. No order can do better, because 11 bytes of data need at least 16 bytes once the size must be a multiple of 8.


c) The monitor keeps a buffer of 1000 packets as an array. How much memory does the reordering save for the whole buffer?


An array of NN elements occupies exactly N×sizeofN \times \text{sizeof} bytes with no gaps between elements, because sizeof already includes trailing padding.


The original layout needs 1000 × 24 = ________, and the reordered layout needs 1000 × 16 = ________.


24000−16000=8000 bytes24000 - 16000 = 8000\ \text{bytes}


Reordering saves 8000 bytes, one third of the original buffer, without changing any member.


d) The same members are put in union packet_u { char flag; double time; short port; };. Find sizeof(union packet_u) and describe what u.flag reads after u.time = 1.5;.


All three members start at offset 0. The largest member is time at 8 bytes, and the strictest alignment is also 8, so no rounding is needed:


sizeof=8⌈88⌉=8 bytes\text{sizeof} = 8 \left\lceil \frac{8}{8} \right\rceil = 8\ \text{bytes}


After u.time = 1.5; all 8 bytes hold the double 1.5, whose IEEE 754 bit pattern is 0x3FF8000000000000. u.flag reads only the byte at offset 0. On x86-64, which is little-endian, that byte is the least significant one, 0x00, so u.flag reads 0 rather than any flag value stored earlier.


The union is 8 bytes, and reading flag after storing time reinterprets part of the double instead of recovering a separate value.

Match each term about C structures and unions with the description that fits it. Each description is used exactly once.

Match each term
A.

A user-defined type whose named fields each occupy their own storage, laid out in declaration order

B.

The number that every address of an object of a given type must be a multiple of

C.

The distance in bytes from the start of an object to the start of one of its fields

D.

Unused bytes the compiler inserts so the next field, or the next array element, starts at a properly aligned address

E.

A user-defined type whose fields all begin at offset 0 and overlap in the same storage

F.

A named field declared inside the braces of a struct or union type

Alignment requirement

Offset

Union

Member

Structure

Padding

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A retry tracker uses the following C17 structure declaration. The uppercase word MEMBER is a placeholder for a member name.


C
struct RetryState {
    int status;
    int attempts;
};

struct RetryState tracker = { .MEMBER = 3 };


Complete both statements so that the initializer explicitly sets only the attempts member to 3.


Replace MEMBER with . After initialization, tracker.status has the integer value .

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Consider the declaration below on a 64-bit platform where short occupies 2 bytes with 2-byte alignment and float occupies 4 bytes with 4-byte alignment. Select every statement that is true.


C
union reading {
    short s;
    float f;
    char  raw[6];
};
Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice