Link to home
Start Free TrialLog in
Avatar of jweston1
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;
}



Avatar of Member_2_1001466
Member_2_1001466

Due to get variables on predefined memory locations there might be additional bytes added to the struct. For performance reasons variables of length 4 should be on memory locations with the last two bits 0. Try the example again with
struct a {
  short b1;
  short b2;
  long c;
}

and
offsetof (a, b2) should return 2.
This happens because structure members are aligned to 32-bits boundary.
ASKER CERTIFIED SOLUTION
Avatar of Member_2_1001466
Member_2_1001466

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jweston1

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.