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;
}



LVL 3
jweston1Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

SteHCommented:
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.
0
AlexFMCommented:
This happens because structure members are aligned to 32-bits boundary.
0
SteHCommented:
And have a look at the documentation of
#pragma pack (n)
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclang/html/_predir_pack.asp
to see how to change this behaviour.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
AlexFMCommented:
See /Zp compiler option (Struct Member Alignment).
0
jweston1Author Commented:
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.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.