c2cedge
C, Java & Python · B — C Essentials

C: Structures, Unions & Output Questions

Structs group related data; unions overlap it to save space. Their sizes, access operators and a handful of output puzzles round out the C section.

Test weight: Medium (C)Skill: Aggregate typesDifficulty: Medium

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?
  1. A struct gives each member its own storage, so its size is at least the sum of all members (plus padding).
  2. A union overlaps members in shared memory, so its size equals the largest member.
  3. Example: { int; char } — the struct is ~8 bytes (with padding), the union is 4 bytes.
Worked example
When would you use a union instead of a struct?
  1. When a value can be one of several types but only one at a time, and you want to save memory.
  2. Classic use: a 'variant' or 'tagged' value that may hold an int OR a float OR a char.
  3. You usually pair it with a separate tag field telling you which member is currently valid.
⚠ 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.
Practice this — take a timed mock →
1,300+ questions, scored, with a weak-area report.
Know who's ready. Not who finished.
HomeLibraryPrivacyTerms