Why is sizeof for a structure not equal to the sum of sizeof its members?
Hello, colleagues! I'm a beginner in C++ and recently encountered unexpected behavior. I have a simple structure:\n\n```cpp\nstruct MyStruct {\n char a; // 1 byte\n int b; // 4 bytes\n short c; // 2 bytes\n};\n```\n\nIt's logical to assume that sizeof(MyStruct) would be 1 + 4 + 2 = 7 bytes. But when I output the size via `std::cout`, the compiler shows 12 bytes! Why is that? I'm not using any virtual functions or inheritance. I checked on different compilers (GCC, MSVC) — it's the same everywhere. Also, if I change the order of the fields, the result changes. For example, if I put `int` first, the size becomes 8 bytes. What kind of magic is this? Is it a compiler bug or am I missing something? Please explain how sizeof works for structures and how to
No answers yet.
Log in to leave an answer
Blogs