Jump to content
  • Advertisement
Sign in to follow this  
peter86

sizeof struct

This topic is 4853 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I came across a confusing phenomenon; why is sizeof(myStruct) == 8? struct myStruct { unsigned long numberOne; unsigned short numberTwo; }; If I put the pragmas below around it, the size will be 6, why? When do I need to use this "workaround"? And what does this pragma do? #pragma pack(push, 1) /* ... */ #pragma pack( pop )

Share this post


Link to post
Share on other sites
Advertisement
I would guess the compiler is padding to align the data to 4-byte increments, and that the pragma overides that by instructing the compiler to pack the data together contiguously.

Share this post


Link to post
Share on other sites
it's 8 because it's more effecient for 32 bit cpus to access 4 bytes at a time than 2.

Share this post


Link to post
Share on other sites
Hmm, it seems like we have a couple of these threads each month. Maybe they should mention this in the FAQ.

Share this post


Link to post
Share on other sites
This extra padding (the extra two bytes which are confusing you) is provided to ensure numberOne is allways on a four byte boundry, which allows for more efficient access. You should never need to use this "workaround", but people often (mis)use it to read files by reading in a big chunk of data and then casting a pointer to that data to a pointer to a specific structure.

The pragma sets (pushes), and then unsets (pops), the "pack" option which controls how to align data - pack( push , 1 ) sets this to 1-byte boundries. Depending on your compiler, I believe the default may be something like 8 (meaning the compiler will pad so that any 8-byte type (e.g. __uint64 or similar) will be aligned on an 8-byte boundry (e.g. the address will look like either: 0x_______0 or 0x_______8).

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!