Platform dependency of struct size
What you'll learn: Why the size of a structure can change depending on your computer's architecture and the compiler's rules.
The Tetris of Memory
When you define a struct, you might assume its size is simply the sum of its parts. If a char is 1 byte and an int is 4 bytes, a struct containing one of each should be 5 bytes, right?
Not necessarily. In C, the size of a struct is platform-dependent.
Think of your computer's memory like a warehouse with shelves that are 4 or 8 units wide. The CPU likes to grab data in these specific "word" sizes. If a piece of data starts in the middle of a shelf and spills onto the next one, the CPU has to do double the work to read it. To stay fast, the compiler adds invisible "padding" bytes to align data with these shelves.
Seeing the Padding
Depending on whether you are on a 32-bit or 64-bit system, or which compiler you use, the "gaps" between your variables will change.
#include <stdio.h>
struct Data {
char a; // 1 byte
// 3 bytes of invisible padding might be added here!
int b; // 4 bytes
};
int main() {
struct Data myData;
printf("Size of char: %zu\n", sizeof(char));
printf("Size of int: %zu\n", sizeof(int));
printf("Actual size of struct: %zu\n", sizeof(myData));
return 0;
}
On most modern systems, the output for the struct size will be 8, not 5. The compiler inserted 3 bytes of empty space after the char so that the int starts on a clean 4-byte boundary.
Why This Matters
Because these rules change between platforms, you cannot assume a struct will take up the same amount of space on a tiny microcontroller as it does on a powerful desktop.
If you save a struct to a file on a Windows PC and try to read it directly into a struct on a different system (like an Arduino or a Mac), the padding might be in different places. This would cause your data to look like gibberish! This is why professional programmers always use the sizeof() operator rather than hard-coding numbers.
Key takeaway
A struct's size is often larger than the sum of its members because the compiler adds padding to satisfy platform-specific alignment requirements.