+ 5
Why depends the result on order of declaration of class, or struct members?
struct test { char a; int c; char b; }; struct test1 { char a;char b; int c; }; class test2 { char a; int c; char b; }; class test3 { char a; char b; int c; }; int main() { std::cout << sizeof(test) << std::endl; std::cout << sizeof(test1) << std::endl; std::cout << sizeof(test2) << std::endl; std::cout << sizeof(test3) << std::endl; std::cin.get(); return 0; }
2 Réponses
+ 3
Thanks @C++ Soldier (Babak) .
+ 2
This SO Wiki addressed the question
"Why does the sizeof operator return a size larger for a structure than the total sizes of the structure's members?"
Like so
"This is because of padding added to satisfy alignment constraints. [...] ¹"
Note: See the example there.
_____
¹ https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member