A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
The compiler inserts unnamed padding bytes between struct members to satisfy alignment requirements. A 4-byte int must start at an address divisible by 4. An 8-byte double must start at an address divisible by 8. If a char is followed by an int, the compiler inserts 3 padding bytes after the char so the int starts on a 4-byte boundary. The struct's total size is padded to a multiple of its strictest alignment. This means a struct with 1 + 4 + 8 bytes of members is not 13 bytes. It is 16.
#include <stdio.h>#include <stddef.h>struct Bad {char flag;int value;double weight;};struct Good {double weight;int value;char flag;};int main(void) {printf("struct Bad:\n");printf(" sizeof: %zu\n", sizeof(struct Bad));printf(" flag at: %zu\n", offsetof(struct Bad, flag));printf(" value at: %zu\n", offsetof(struct Bad, value));printf(" weight at: %zu\n", offsetof(struct Bad, weight));printf("\nstruct Good:\n");printf(" sizeof: %zu\n", sizeof(struct Good));printf(" weight at: %zu\n", offsetof(struct Good, weight));printf(" value at: %zu\n", offsetof(struct Good, value));printf(" flag at: %zu\n", offsetof(struct Good, flag));return 0;}
Both structs are 16 bytes. In Bad, the char at offset 0 is followed by 3 padding bytes so the int can start at offset 4. The int ends at offset 8, where the double naturally aligns. In Good, the double is first (offset 0), the int follows at offset 8, and the char at offset 12. Three padding bytes at the end round the total to 16. The member order changed the internal layout but not the total size in this case. For other combinations, reordering can save bytes.
#include <stdio.h>struct Wasteful {char a;int b;char c;int d;char e;};struct Compact {int b;int d;char a;char c;char e;};int main(void) {printf("Wasteful: %zu bytes\n", sizeof(struct Wasteful));printf("Compact: %zu bytes\n", sizeof(struct Compact));return 0;}
Same members. Different order. 8 bytes saved. The Wasteful struct has 3 padding bytes after each char to align the following int. The Compact struct groups the ints together and the chars together, requiring only 1 padding byte at the end. In an array of a million such structs, that is 8 MB of wasted memory. Order your members from largest to smallest alignment to minimize padding.
Structure padding is invisible until you check sizeof. Order members by decreasing alignment to minimize waste. Use offsetof to inspect the layout. In binary protocols, use packed attributes or explicit serialization to avoid padding in wire formats. Next: designated initializers, the C99 feature that lets you name struct members in initializers.
Finish the lesson once you have worked through the material. This awards ★ 30 XP.