Quiz Entry - updated: 2026.07.10
How do arrays of structs work in memory?
Array elements must be evenly spaced and each one still has to be aligned, so the struct carries trailing padding making its size a multiple of its largest alignment — sizeof(S3) is 12, not 10.
* sizeof(S3)=12, not 10: trailing padding keeps every element's float v on a 4-byte boundary. *
Example:
struct S3 {
// 2 bytes
short i;
// 4 bytes @ offset 4 (after 2 bytes padding)
float v;
// 2 bytes @ offset 8
short j;
// sizeof(S3) = 12 (not 10!)
} a[10];
Memory layout:
a[0] a[1]
| i |pad| v | v | v | v | j |pad|pad| i |pad| ...
0 2 4 8 10 12 14
Why trailing padding?
- Array elements must be evenly spaced:
&a[1] - &a[0] == sizeof(struct S3) - Each
a[i]must havevat a 4-byte aligned address - Without trailing padding,
a[1].vwould be at offset 22 (misaligned!)
Address calculations:
// Address of a[i]
addr = base + i * sizeof(struct S3)
// Address of a[i].j
addr = base + i * sizeof(struct S3) + offsetof(struct S3, j)
= base + i * 12 + 8
In assembly, you'll see:
; Access a[idx].j where idx is in %rdi
imul $12, %rdi, %rax ; offset = idx * 12
movw 8(%rax), %ax ; load j from offset 8 within struct
Tip: Use offsetof(type, member) from <stddef.h> to get member offsets portably.
Go deeper:
Data structure alignment — Wikipedia — why every array element carries trailing padding.