What is the alignment of a struct member with 64-bit pointers?

  • Thread starter Thread starter Manda Rajo
  • Start date Start date
M

Manda Rajo

Guest
Hi, everytime I use a 64-bit pointer in a struct, then I don't understand the behavior of the size of the struct. Can you explain why, or is there a documentation? Thanks.
It's true that I can ignore the behavior, but for mentally verification purpose, every-time I use a "sizeof" then the result is illogical, I mean when I mentally verify the "sizeof" of the struct then the calculus is wrong:

(sizeof(int)) + 4 * (sizeof(int)) + (sizeof(void *)) + (sizeof(int)) + 2 * (sizeof(void *)) == 48, it's wrong because it's not 56

It seems a bug, because the alignment maybe 24 bytes or it maybe 40, that's illogical, it should be multiple of 8 bytes or 16 bytes. I use Visual Studio 2015.

struct MyStruct
{
int x; // Offset: 0

int a; // Offset: 4
int b; // Offset: 8
int c; // Offset: 12
int d; // Offset: 16

//?????? Offset: 20 <-- Why is this empty?

void *ptr0; // Offset: 24 <-- Why is this not 20?
int y; // Offset: 32

//?????? Offset: 36 <-- Why is this empty?

void *ptr1; // Offset: 40
void *ptr2; // Offset: 48 // <-- Why there is no empty before this?
};

size_t size = sizeof MyStruct; // Size: 56

MyStruct s;
int offset;
offset = (char *)&s.x - (char *)&s; // 0
offset = (char *)&s.a - (char *)&s; // 4
offset = (char *)&s.b - (char *)&s; // 8
offset = (char *)&s.c - (char *)&s; // 12
offset = (char *)&s.d - (char *)&s; // 16
offset = (char *)&s.ptr0 - (char *)&s; // 24
offset = (char *)&s.y - (char *)&s; // 32
offset = (char *)&s.ptr1 - (char *)&s; // 40
offset = (char *)&s.ptr2 - (char *)&s; // 48

Continue reading...
 
Back
Top