A struct groups several named fields into one type; each field has its own memory. A union overlaps all its members in the same memory, so it's only as big as its largest member and can hold one of them at a time. Knowing their sizes, the . vs -> access rule, and alignment makes the common output questions easy.
struct stores all; union shares one
A struct's size is at least the sum of its members (plus padding for alignment). A union's size is that of its largest member, because all members share the same memory — writing one overwrites the others. Access a member with . on a struct value, and -> through a pointer.
struct vs union
struct Point { int x; int y; }; // size >= 8 (two ints, maybe padding)
union Value { int i; char c; }; // size = 4 (largest member); i and c overlap
struct Point p = {1, 2};
p.x = 5; // dot for a value
struct Point *pp = &p;
pp->y = 9; // arrow through a pointer⚡ The edge
- A struct allocates space for every member; a union allocates space for only the largest, shared by all. In a union, writing one member corrupts the others — only one holds a valid value at a time.
- Use . on a struct/union value and -> through a pointer to one. pp->y is shorthand for (*pp).y. Struct sizes can also include padding for alignment, so they may exceed the naive sum.
Worked example
What is the difference in size between a struct and a union of the same members?
- A struct gives each member its own storage, so its size is at least the sum of all members (plus padding).
- A union overlaps members in shared memory, so its size equals the largest member.
- Example: { int; char } — the struct is ~8 bytes (with padding), the union is 4 bytes.
Answer: A struct's size is the sum of members (plus padding); a union's size is just its largest member.
Worked example
When would you use a union instead of a struct?
- When a value can be one of several types but only one at a time, and you want to save memory.
- Classic use: a 'variant' or 'tagged' value that may hold an int OR a float OR a char.
- You usually pair it with a separate tag field telling you which member is currently valid.
Answer: When a value holds one of several types at a time and you want to save memory — e.g. a tagged variant.
⚠ Watch out
- Padding/alignment can make a struct larger than the naive sum of its members.
- . vs ->: use . on a value, -> on a pointer — mixing them is a compile error.
- In a union, only the most recently written member is valid; reading another is undefined.