C Struct Padding
In this page:
Why Padding Exists
Most CPUs read multi-byte values fastest when they sit at a memory address that's a multiple of their own size -- a 4-byte int is fastest read from an address divisible by 4 -- so the compiler inserts unused padding bytes between struct members to keep each field aligned this way.
Example: Why Padding Exists
#include <stdio.h>
struct Example {
char c;
int i;
};
int main() {
printf("%zu", sizeof(struct Example));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Seeing Padding with sizeof
A struct containing a char followed by an int often reports a sizeof larger than the sum of its members' individual sizes -- the compiler silently inserted 3 padding bytes after the char so the following int lands on a 4-byte boundary.
Example: Seeing Padding with sizeof
#include <stdio.h>
struct Mixed {
char c;
int i;
};
int main() {
printf("%zu %zu %zu", sizeof(char), sizeof(int), sizeof(struct Mixed));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Field Order Affects Total Size
Reordering a struct's members can shrink or grow its total size even though the fields themselves haven't changed -- grouping larger types together and placing smaller ones like char at the end typically minimizes the padding the compiler needs to insert.
Example: Field Order Affects Total Size
#include <stdio.h>
struct Ordered {
int i;
char c;
};
struct Reordered {
char c;
int i;
};
int main() {
printf("%zu %zu", sizeof(struct Ordered), sizeof(struct Reordered));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Padding at the End of a Struct
Compilers also add trailing padding after a struct's last member so that the struct's overall size is a multiple of its strictest member's alignment requirement, which matters when the struct is used inside an array so each element stays properly aligned.
Example: Padding at the End of a Struct
#include <stdio.h>
struct Trailing {
int i;
char c;
};
int main() {
printf("%zu", sizeof(struct Trailing));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Disabling Padding When It Matters
Compiler-specific directives like #pragma pack(1) can force a struct to be packed with no padding at all, which matters when matching an exact binary file format or network protocol layout, but reading unaligned fields this way can be slower or even fault on some hardware.
Example: Disabling Padding When It Matters
#include <stdio.h>
#pragma pack(1)
struct Packed {
char c;
int i;
};
#pragma pack()
int main() {
printf("%zu", sizeof(struct Packed));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: