Module 12 · Structures, Unions and Enums
Under the Hood: Padding, Alignment and sizeof Surprises
ProReading
Kenji wants to keep a million sensor records in memory. Each record is a char, an int and another char. He adds up the fields: 1 + 4 + 1 is 6 bytes, so a million records need 6,000,000 bytes. Then he asks the Playground for sizeof, and it prints 12.
Pro lesson
This one goes deeper
It is included with this track and with Learn Pro. Every question on the Skill Test can be answered from the free lessons, so this is depth and never a gate on the certificate.
What is inside Under the Hood: Padding, Alignment and sizeof Surprises
- sizeof surprises: six bytes of fields, twelve bytes of struct
- offsetof: where each field starts
- The rule: every field starts at a multiple of its alignment
- The padding at the end keeps an array aligned
- Reordering fields to shrink a struct
- Why alignment exists
- Padding bytes hold anything, so compare field by field
- packed: no padding, and not portable