Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the sizeof a struct different from the sum of its members? [duplicate]

Tags:

c

sizeof

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}

};
like image 464
bamboolouie Avatar asked Dec 28 '22 15:12

bamboolouie


1 Answers

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.

like image 53
Michael Burr Avatar answered Jan 05 '23 00:01

Michael Burr