How does the compiler handle alignment inside structures?
The compiler inserts invisible padding bytes between fields so each one lands on its required alignment, and pads the whole struct out to a multiple of its largest member's alignment.
* The compiler pads fields to their alignment; reordering members largest-to-smallest shrinks this struct from 24 to 16 bytes. *
You declare fields in an order; the compiler is obligated to place each at a correctly aligned offset, inserting gaps where needed. That's why a struct is often larger than the sum of its fields:
struct example {
char a; // offset 0
// 3 bytes padding
int b; // offset 4 (must be multiple of 4)
char c; // offset 8
// 7 bytes padding
long d; // offset 16 (must be multiple of 8)
}; // total: 24 bytes, not 14!
The trailing pad after d rounds the struct up to a multiple of 8 (its largest alignment) so that arrays of the struct stay aligned automatically.
Optimization tip: order members from largest to smallest alignment to minimise padding. Reordering the struct above puts long d, then int b, then the two chars, shrinking it from 24 bytes to 16 — a real saving when you allocate millions of them.
Go deeper:
Data structure alignment (Wikipedia) — struct padding, field offsets, and reordering to shrink structs.