C Programming · Interview question

Why is sizeof a struct often larger than the sum of its members?

A strong answer

Because of padding inserted to satisfy alignment requirements. Most architectures require (or strongly prefer) that a value of size N start at an address that's a multiple of N, a 4-byte int on a 4-byte boundary. The compiler inserts padding bytes between members so each lands on its natural boundary, and adds tail padding so that in an array of the struct, every element stays aligned. For example, struct { uint16_t a; uint32_t b; uint8_t c; } has fields summing to 7 bytes but typically sizeof 12: 2 bytes of a, 2 padding to align b, 4 of b, 1 of c, 3 tail padding. You can minimize padding by ordering members largest-alignment-first. This matters because misaligned access is slow on x86 and outright faults on some ARM cores, so the padding isn't waste, it's what keeps access legal and fast.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Structs, Unions & Bitfields

Group related data, overlay the same bytes two ways, and pack flags into bits, plus the padding and alignment rules that decide sizeof and bite packet parsing.

More Structs, Unions & Bitfields questions

Browse all 472 interview questions