Structs & memory layout
Your struct is bigger than the sum of its fields, and the field order decides by how much.
Before you start
A **struct** groups related fields under one name — instead of three loose variables x, y, z, you have one Point with .x, .y, .z. Nothing new happens in memory; the fields just sit next to each other.
Except the fields do *not* always sit next to each other. Computers read memory faster when values sit on "nice" addresses divisible by the value's size. So the compiler quietly inserts empty bytes — **padding** — to keep everyone aligned.
This lesson shows why sizeof(struct) is often bigger than you expect, and why reordering the fields by size can shrink your struct by 30% without changing anything the program does.
Bytes in memory
one square = one bytePacked end to end — plausible, and not what any mainstream compiler produces.
Step 1 of 7. The size you would expect: 7. `struct Point` holds a `char` (1 byte), an `int` (4) and a `short` (2). Add them up and you get 7. `sizeof(struct Point)` is 12. The extra 5 bytes are not a mistake, and they are not overhead the struct needs for bookkeeping — a C struct has no header.
Step 01 / 07
The size you would expect: 7
struct Point holds a char (1 byte), an int (4) and a short (2). Add them up and you get 7.
sizeof(struct Point) is 12. The extra 5 bytes are not a mistake, and they are not overhead the struct needs for bookkeeping — a C struct has no header.
#include <stdio.h>struct Point { char tag; int x; short y;};struct Packed { int x; short y; char tag;};int main(void) { printf("%zu\n", sizeof(struct Point)); /* 12 */ printf("%zu\n", sizeof(struct Packed)); /* 8 */ return 0;}