← The C Language Lesson 45 of 77 · 10 XP

Struct alignment

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

It's easier for the processor to read an int at addresses that are multiples of 4, and a double at multiples of 8. So the compiler aligns the fields of a struct and inserts empty bytes between them — padding:

struct a {
    char c;     // 1 byte
                // 3 bytes of emptiness
    int i;      // 4 bytes, the address is a multiple of 4
};              // sizeof = 8, not 5

struct b {
    char c1;    // 1
                // 3 empty
    int i;      // 4
    char c2;    // 1
                // 3 empty — so that the next struct b in an array is aligned too
};              // sizeof = 12

struct c {
    int i;      // 4
    char c1;    // 1
    char c2;    // 1
                // 2 empty
};              // sizeof = 8 — the same fields, a different order

The rule: arrange the fields from largest to smallest, and there will be fewer empty bytes. This matters when there are millions of structs (games, databases, an OS kernel).

offsetof(struct b, i) from <stddef.h> helps you find out a field's offset.

Task. Print, separated by spaces, the sizeof of three structs: struct a { char c; int i; }, struct b { char c1; int i; char c2; } and the same b with its fields reordered, struct c { int i; char c1; char c2; }.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.