This question already has an answer here:
-
How is the size of a C++ class determined?
4 answers
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 your system, pointers are 8 bytes and aligned to 8 bytes.
1 2 3 4 5 6 7 8
+---+---+---+---+---+---+---+---+
| int i | [pad] |
+---+---+---+---+---+---+---+---+
9 10 11 12 13 14 15 16
+---+---+---+---+---+---+---+---+
| int *p |
+---+---+---+---+---+---+---+---+
17 18 19 20 21 22 23 24
+---+---+---+---+---+---+---+---+
| c | un | [pad] |
+---+---+---+---+---+---+---+---+
Of course, you cannot be sure of the exact layout without knowing the ABI. The above is only an example.
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 between i
and p
. Furthermore, because int *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 for p
.
So, you end up with a layout like this:
i
: 4 bytes, alignment 4
- pad: 4 bytes
p
: 8 bytes, alignment 8
c
: 1 bytes
un
: 4 bytes (as it can remain byte aligned)
- pad: 3 bytes (to round it out to an 8 byte boundary)