With C/C++ structs, normally, the final struct's size is the plain sum of the sizes of all its elements, but there are cases which this is not true.
I am looking at the technical answer (it has to be one) of why the following struct's size is not equal to the size of all its members:
#include <iostream>
struct {
int a;
long b;
char c;
} typedef MyStruct;
int main() {
MyStruct sss;
std::cout << "Size of int: " << sizeof(int) << std::endl << "Size of long: " << sizeof(long) << std::endl << "Size of char: " << sizeof(char) << std::endl;
std::cout << "Size of MyStruct: " << sizeof(sss) << std::endl;
return 0;
}
Thas has the following output:
Size of int: 4
Size of long: 8
Size of char: 1
Size of MyStruct: 24
So it can be seen than the size of MyStruct
is not 4+8+1 (13)
rather, it is actually 24
, but why?