jweston1
asked on
C++ offsetof macro
Can someone tell me why the offsetof macro is not returning the correct result? The offset of c is clearly 2 bytes, yet Visual C++ 6.0 returns a value of 4 for the offset. Thanks.
#include "stdafx.h"
#include <windows.h>
#include <stddef.h>
struct a
{
short b; //0x00
long c; //0x02
};
int main(int argc, char* argv[])
{
DWORD d = offsetof(a,c); //0x04
return 0;
}
#include "stdafx.h"
#include <windows.h>
#include <stddef.h>
struct a
{
short b; //0x00
long c; //0x02
};
int main(int argc, char* argv[])
{
DWORD d = offsetof(a,c); //0x04
return 0;
}
This happens because structure members are aligned to 32-bits boundary.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
It seems the compiler is allocating a long for the short even though I've specified it as short. Maybe this is for alignment or something.
struct a {
short b1;
short b2;
long c;
}
and
offsetof (a, b2) should return 2.