struct s11
{
alignas(16) char s;
int i;
};
does
alignas(n) X xmean it would allocate n bytes to hold aX, whenXis actually much smaller than n bytes, the rest memory would be all 0s?when
s11.sis in memory0x0, does that means11.iwould be at0x10? However, the followingpdiffis0x4
s11 o;
ptrdiff_t pdiff = (char*)&o.i - (char*)&o.s;
- Please explain why
sizeof(s11)is not 16 times 2, whilesizeof(s1)is 8 times 3?
struct s1
{
char s;
double d; // alignof(double) is 8.
int i;
}
EDIT: This is what I found after a lot of digging and code snippets, that how alignas affect struct(class) size.
alignas(n) X x means in memory x is located at a place with an offset of multiple of n bytes, starts from 0x00. Therefore, s11.s can be located at 0x00, 0x10, 0x20 and so on. Because s11.s is the first field, it is at 0x00, and it is a char, so it ocupies 1 bytes.
So is the 2nd field. int has an align 4, therefore it can be located at 0x00, 0x04, 0x08, 0x0c, etc. Because the first byte is taken by s11.s, so s11.i is located at 0x04.