← 🧱 Structs, Unions & Undefined Behaviour
Subtopic 2 of 4

7.2Padding, alignment and sizeof

The idea

The compiler inserts padding so each member starts at an address divisible by its own size, and the whole struct size is a multiple of its largest member.

Think of it like this: Parking spaces sized by vehicle: a truck needs a slot that starts on a truck-sized boundary, so small cars before it leave unused gaps.

Why it exists

sizeof(struct) is often bigger than the sum of the members, and the order of members changes it.

How it works

  1. Start with offset 0.
  2. Round the offset up to a multiple of the member's alignment, then place the member.
  3. After the last member, round the total up to a multiple of the largest alignment.
  4. Putting big members first usually reduces padding.

Worked example: struct { char a; int b; char c; }

a at 0; b rounded up to 4 (3 padding bytes); c at 8; total 9 rounded up to 12. Reordered as int, char, char the size is 8.

Now play with it

  • →Open the second preset and compare "char, int, char" with "int, char, char".
  • →Change types in the table to see how offsets move.
membertypecountoffsetsizepadding before
a010
b443
c810
sum of member sizes6
tail padding3
alignment of the struct4
sizeof(struct)12
sizeof if members sorted largest first8

Each member starts at a multiple of its own size; the whole struct is rounded up to a multiple of the largest member size. In the first preset grade sits at offset 400, which is the displacement an index-addressing instruction would use.

Member typeSizeMust start at a multiple of
char11
short22
int, float44
long, double, pointer88
array of Tn × size of Talignment of T
structrounded up sizelargest member alignment

Rule of thumb: padding goes before a member that is not aligned, and at the end so that arrays of the struct stay aligned.

Check yourself

struct { char c; double d; } has size

Remember: Align each member to its size, round the total up to the largest alignment.
Exam notes (the dense version)

Each member is aligned to its own size (an int at a multiple of 4, a double at a multiple of 8) and the struct size is rounded up to a multiple of the largest alignment. The compiler inserts padding bytes to achieve this, so sizeof(struct) can be larger than the sum of the members. Putting large members first usually wastes less space. Packed structs remove padding.

Previous year questions: Structs, Unions & Undefined Behaviour (2)

PYQs are grouped by topic, so this is the full set for Structs, Unions & Undefined Behaviour; try the ones that match this subtopic. Open all 2 on the topic page.