Sign in to follow this  
DJohnson

structs and memory addressing

Recommended Posts

DJohnson    122
Trying to read a BMP File in C++, but I'm having a few difficulties. Is the memory for the different members of a struct contiguous? code snippets: ------------- struct BMPHeader { BYTE Signature[2]; DWORD FileSize; . . BMPHeader Header; flBitmap.Read(&Header, sizeof(BMPHeader)); -------------- What am I doing wrong here? Signature fills up with the correct data, but FileSize does not. I checked the memory addresses of both; FileSize's address is 4 greater than Signature[0]'s. Shouldn't it be 2 greater? If the data in a struct is not contiguous, is there a way to force it to be, or is there a better way to do this?

Share this post


Link to post
Share on other sites
silvermace    634
thats the compiler adding byte padding so that the elements line up along 4byte boundaries.

to force no-padding in MSVC:

#pragma pack(push, 1)
struct BMPHeader {
// ...
};
#pragma pack(pop)

there is probably something you're missing though
i would suspect the BMP header struct has the members mixed up somehow?
im no BMP expert tho.

EDIT: more info added (MSDN link)

Share this post


Link to post
Share on other sites
DJohnson    122
Thanks man, It's working beautifully. Never would have figured out the byte padding myself. Adding that one line seemed to be all it needed.

Share this post


Link to post
Share on other sites
Spoonbender    1258
This padding is usually done for performance reasons though (it's faster to access data if it's aligned properly), so don't do that little trick unless you have to. ;)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this