This question already has an answer here:
I'm very confused by the whole 'data alignment' thing:
#include <stdio.h>
int main(){
struct st{
int i,*p;
char c;
union { char type[4]; unsigned char d;} un;
};
struct st s1={25,&a,'X',"asdf"};
printf("sizeof s1 is %d",sizeof(s1));
return 0;
}
due to data alignment, i thought that since the sizes of
int i : 4 bytes
int *p : 8 bytes
char c : 1 byte(+3)
union : 4 bytes
the output would be 20, but this outputs sizeof s1 is 24
!
Why is it outputting 24? Does this regard int *p, which is 8 bytes?
On the architecture you're using, the
int *p
is 8 bytes, but needs to be on an 8 byte boundary also. That gives you 4 bytes pad betweeni
andp
. Furthermore, becauseint *p
needs to be on an 8 byte boundary, the overall structure needs to be a multiple of 8 bytes so that an array of them always has the right alignment forp
.So, you end up with a layout like this:
i
: 4 bytes, alignment 4p
: 8 bytes, alignment 8c
: 1 bytesun
: 4 bytes (as it can remain byte aligned)On your system, pointers are 8 bytes and aligned to 8 bytes.
Of course, you cannot be sure of the exact layout without knowing the ABI. The above is only an example.