typestar

sizeof and alignment in C

sizeof measures storage, and a struct is usually bigger than the sum of its fields.

#include <stddef.h>
#include <stdio.h>

struct Padded {
    char flag;
    int count;
    char label;
};

void layout(void) {
    printf("char %zu int %zu double %zu\n",
           sizeof(char), sizeof(int), sizeof(double));
    printf("struct %zu, fields %zu\n",
           sizeof(struct Padded), sizeof(char) * 2 + sizeof(int));
    printf("offsets %zu %zu %zu\n",
           offsetof(struct Padded, flag),
           offsetof(struct Padded, count),
           offsetof(struct Padded, label));
    printf("alignment %zu\n", _Alignof(struct Padded));
}

How it works

  1. sizeof is evaluated at compile time and yields a size_t.
  2. Padding aligns each member to its own requirement.
  3. offsetof shows you exactly where the holes are.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
470
Tokens
122
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 81 seconds.

Type this snippet

Step 1 of 4 in Values & storage, step 27 of 35 in Language basics.

← Previous Next →