Jump to content
  • Advertisement
Sign in to follow this  
Endemoniada

sizeof() not working ?!?

This topic is 2092 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

Hi guys, I am having a hard time understanding something right now:

 

struct FormatChunk
{
 BYTE subchunk1ID[4];
 DWORD subchunk1Size;
 short audioFormat;
};
 
DWORD dwSize=sizeof(FormatChunk); // is 12  !!!!
dwSize=sizeof(short); // is 2 like it should be

 

What the hell ?

 

Share this post


Link to post
Share on other sites
Advertisement
structs are usually padded to a 4 byte boundary. If you are using MSVC, you can control the packing, check out #pragma pack. If you can afford the memory, go with the usual packing though (it's more efficient to read DWORDs off 4 byte boundaries usually). Packing is important if you are worried about data file size or sending it acros a network, however.

Share this post


Link to post
Share on other sites

Ahh, ok guys, I thought I was going crazy.

 

I'm going to read up on it.

 

In general though, if I have to read 10 bytes into that struct I can't rely on sizeof() and should explicitly set it to read 10, is that right ?

 

Thanks.

 

Share this post


Link to post
Share on other sites

Your safest option is to read and write each element individually.

 

sizeof(subchunk1ID) + sizeof(subchunk1Size) +  sizeof(audioFormat) will always be 10 regardless of any structure padding.

Share this post


Link to post
Share on other sites

The best option is typically to use #pragma pack (with push/pop). This allows you to eliminate the padding entirely (using a pack of 1), and at that point the representation in memory should be identical to that on disk (barring endian issues, which you are far less likely to run into since Mac's switched to Intel).

 

However, be aware that there is a performance penalty to read/write unaligned memory - you should only pack structures directly involved in I/O.

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!