4

Possible Duplicate:
Why isn't sizeof for a struct equal to the sum of sizeof of each member?

If I implement below code, my output of sizeof(*zip) is 56. [10 + 10 + 4 + 4*8]byte = 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 below code, my output of sizeof(*zip) is 440. [100 + 100 + 100 + 100 + 4 + 4*8] = 436, my question is where is another 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}

};
Community
  • 1
  • 1
bamboolouie
  • 57
  • 2
  • 6

4 Answers4

6

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

The specific answer is that your compiler is probably aligning the double members on an 8 byte boundary. In the first example that requires no padding. In the second example it requires 4 bytes of padding after the int c member.

Michael Burr
  • 333,147
  • 50
  • 533
  • 760
3

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

Andreas Brinck
  • 51,293
  • 14
  • 84
  • 114
1

A C implementation is allowed to add padding to a struct to ensure that both the members of the struct are optimally aligned for the target platform and so the instances of the struct itself are aligned when an array of them is formed.

The particular alignment that the implementation chooses may depend on the size of a particular struct as well as the types and layout of its members.

CB Bailey
  • 755,051
  • 104
  • 632
  • 656
0

If you want to make your struct more memory efficient use #pragma pack(push,1) before it and #pragma pack(pop) afterwards. This will be at the expensive if speed, and possibly to a lesser extent, code size.

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

SmacL
  • 22,555
  • 12
  • 95
  • 149