Possible Duplicate:
C struct sizes inconsistence
For the following program, i’d like to obtain the size of a struct. However, it turns the size of it is 12 rather than 4*4=16. Does it means that each element can align to a different pad number? like int with 4 and short with 2, but in this case char should have 1.
Thx.
#include <stdio.h>
struct test{
int a;
char b;
short c;
int d;
};
struct test A={1,2,3,4};
int main()
{
printf("0X%08X\n",&A.a);
printf("0X%08X\n",&A.b);
printf("0X%08X\n",&A.c);
printf("0X%08X\n",&A.d);
printf("%d\n",sizeof(A));
}
And the result is:
0X00424A30
0X00424A34
0X00424A36
0X00424A38
12
Yes, every type don’t have the same alignment. Each of your variable shall be aligned correctly, ie their addresses shall be a multiple of a certain size. The usual rule (for Intel and AMD, among other) is that every data type is aligned by its own size. Assuming x86 architecture, it seems to be right here:
0X00424A30: first address of the structure.0X00424A34: 4 bytes (maybesizeof(int)) after the first member.charrequires an alignment of1, so it doesn’t need padding here.0X00424A36: 2 bytes after the second member.shortrequires an alignment of 2, so there is 1 byte of padding.0X00424A38: 2 bytes after the second member.intrequires an alignment of 4, but the address is already a multiple of 4. So there is no padding byte.Anyway, it is not portable assumption: C standard doesn’t force anything here. It just allow padding bytes between your members and at the end of the structure.
By the way, you should rather use the following formats:
%pand typecast for pointers;%zuor%uwith typecast forsizeof.