Offsetof Macro in C

Level 5325 keystrokes

Uses offsetof to print the byte position of each member of a struct mixing char, int and double, showing the padding added for alignment. On a typical 64-bit system the offsets are 0, 4, 8 and 16 and the struct is 24 bytes.

C code

// Members of different sizes; the compiler inserts padding so each one is aligned
1struct Data {
// 1 byte at offset 0
2 char a;
// 4 bytes at offset 4, after 3 padding bytes
3 int b;
// 1 byte at offset 8, right after b
4 char c;
// 8 bytes that need 8-byte alignment: offset 16, after 7 padding bytes
5 double d;
6};
7
// 16 + 8 = 24 bytes in total, padding included
8printf("Struct size: %lu\n", sizeof(struct Data));
// offsetof(type, member) gives the member's distance in bytes from the start: 0
9printf("Offset of a: %lu\n", offsetof(struct Data, a));
// Prints 4, showing the 3 padding bytes after a
10printf("Offset of b: %lu\n", offsetof(struct Data, b));
// Prints 8: c follows b directly
11printf("Offset of c: %lu\n", offsetof(struct Data, c));
// Prints 16, the next multiple of 8 after c
12printf("Offset of d: %lu\n", offsetof(struct Data, d));

Output

Struct size: 24
Offset of a: 0
Offset of b: 4
Offset of c: 8
Offset of d: 16
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • ;× 10
  • "× 10
  • (× 10
  • )× 10
  • ,× 9
  • :× 5
  • \× 5
  • %× 5
  • {× 1
  • }× 1

More C examples at level 5

← C typing practice