c / intermediate
Snippet
Structural Padding and offsetof
Compilers insert 'padding' bytes between structure members to ensure they are aligned with memory boundaries for performance. The 'offsetof' macro from 'stddef.h' allows you to see the exact byte offset of a member within the structure.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>#include <stddef.h>struct Data {char a;int b;char c;};int main() {printf("Size of struct: %zu\n", sizeof(struct Data));printf("Offset of b: %zu\n", offsetof(struct Data, b));printf("Offset of c: %zu\n", offsetof(struct Data, c));return 0;}
Breakdown
1
struct Data { ... };
A structure where alignment requirements will likely cause the total size to be larger than the sum of its parts.
2
offsetof(struct Data, b)
Returns the number of bytes from the start of the struct to member 'b'.