Example 1 — Copying a struct and measuring padding
A copy is independent of the original; padding inflates the size.
#include <stdio.h>
#include <stddef.h>
struct Point { int x, y; };
struct Packet { char tag; int id; };
int main(void) {
struct Point p1 = {1, 2};
struct Point p2 = p1;
p2.x = 10;
printf("p1 = (%d, %d)\n", p1.x, p1.y);
printf("p2 = (%d, %d)\n", p2.x, p2.y);
printf("sizeof Packet = %zu\n", sizeof(struct Packet));
printf("offset of id = %zu\n", offsetof(struct Packet, id));
return 0;
} How It Works
p2is a copy, so changingp2.xleavesp1alone.chartakes 1 byte, then 3 bytes of padding align theint.- Sizes shown are typical for 32-bit and 64-bit desktop compilers.
