Why is the size of the structure different from the sum of its members?

Possible duplicate:
Why is the sizeof size for the structure not equal to the sum of the sizeof of each member?

If I implement the code below, my output of sizeof (* zip) is 56. [10 + 10 + 4 + 4 * 8] bytes = 56

typedef struct{ char a[10]; char b[10]; int c; double d,f,g,h; }abc_test; abc_test zip[] = { {"Name" ,"Gender", 0,100,200,300,400}, {"Name" ,"Gender", 0,100,200,300,400} }; 

But when I implement the code below, my output of sizeof (* zip) is 440. [100 + 100 + 100 + 100 + 4 + 4 * 8] = 436, my question is: where else 4?

 typedef struct{ char a[100]; char b[100]; char i[100]; char j[100]; int c; double d,f,g,h; }abc_test; abc_test zip[] = { {"Name" ,"Gender","age","mode", 0,100,200,300,400}, {"Name" ,"Gender","age","mode", 0,100,200,300,400} }; 
+4
source share
4 answers

The general answer is that compilers are free to add padding between members for any purpose (usually alignment requirements).

The specific answer is that your compiler probably aligns the double elements at a border of 8 bytes. In the first example, which does not require filling. In the second example, an int c element requires 4 bytes of padding.

+6
source

You may have a compiler that aligns everything to 8 bytes.

+3
source

AC implementations are allowed to add an addition to the structure to ensure that both elements of the structure are optimally aligned for the target platform, and therefore instances of the structure itself are aligned when an array of them is formed.

The exact alignment that the implementation chooses may depend on the size of the particular structure, as well as the types and layout of its elements.

+1
source

If you want to make your structure more memory efficient, use #pragma pack (push, 1) before this and #pragma pack (pop). It will be expensive if the speed and, to a lesser extent, the size of the code.

See http://www.cplusplus.com/forum/general/14659/

0
source

All Articles