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
sizeofis evaluated at compile time and yields asize_t.- Padding aligns each member to its own requirement.
offsetofshows you exactly where the holes are.
Keywords and builtins used here
Padded_Alignofchardoubleintlayoutsizeofstructvoid
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.
Step 1 of 4 in Values & storage, step 27 of 35 in Language basics.