Home > Article > Backend Development > Why in C/C++, the sizeof of the structure is not equal to the sum of the sizeof of each member?
sizeof() The size of the structure type elements obtained is not always equal to the size of each individual member. Sometimes the compiler adds some padding to avoid alignment problems. So dimensions may change. Padding is added when a structure member is followed by a member of larger size or is at the end of the structure. Different compilers have different types of alignment constraints. In the C standard, the total alignment structure is implementation-dependent.
In this case, the double z is 8 bytes long, which is larger than x (4 bytes). So another 4 bytes of padding are added. Additionally, the short type data y has 2 bytes of space in memory, so an extra 6 bytes are added as padding.
#include <stdio.h> struct myStruct { int x; //Integer takes 4 bytes, and padding 4 bytes double z; //Size of double is 8-byte, no padding short int y; //Size of short is 2-byte, padding 6-bytes }; main() { printf("Size of struct: %d", sizeof(struct myStruct)); }
Size of struct: 24
In this case, first insert the double Precision number, which occupies 8 bytes of space. Now the integer x (4 bytes) is added. So there's still another 4 bytes of space. After adding the short y, it can be put into an additional 4 bytes of space, taking up a total of 16 bytes of space.
#include <stdio.h> struct myStruct { double z; //Size of double is 8-byte, no padding int x; //Integer takes 4 bytes, and padding 4 bytes short int y; //Size of short is 2-byte, padding 6-bytes }; main() { printf("Size of struct: %d", sizeof(struct myStruct)); }
Size of struct: 16
The third case also takes up 16 bytes memory space, but arranged in different ways. Since the first member is a double, it is placed first, and then the short type data is added. Now, when an integer is attempted to be inserted, it can be placed into the remaining 6-byte area. Therefore, there is a padding after the short, but no padding after the integer data.
#include <stdio.h> struct myStruct { double z; //Size of double is 8-byte, no padding short int y; //Size of short is 2-byte, padding 6-bytes int x; //Integer takes 4 bytes, and padding 4 bytes }; main() { printf("Size of struct: %d", sizeof(struct myStruct)); }
Size of struct: 16
The above is the detailed content of Why in C/C++, the sizeof of the structure is not equal to the sum of the sizeof of each member?. For more information, please follow other related articles on the PHP Chinese website!