Why is sizeof(struct) not equal to the sum of sizeof all its fields in C++?
Hi! I started learning C++ and encountered some confusing behavior. I have a simple struct:
```cpp
struct MyStruct {
char c; // 1 byte
int i; // 4 bytes
short s; // 2 bytes
};
```
Logically, I expect the size of this struct to be 1 + 4 + 2 = 7 bytes. However, when I output `sizeof(MyStruct)`, the compiler shows 12! Why does this happen? I checked with different field orders, and the size changes. For example, if I put `int` first, the size sometimes becomes 8. Is this a compiler bug or am I missing something? Please explain how memory allocation for structs actually works in C++.
<<>>
Why is the struct size larger than the sum of its fields?
No, this is not a compiler bug. This is a memory feature, on
No answers yet.
Log in to leave an answer