Archived

This topic is now archived and is closed to further replies.

Wavarian

Quick question

Recommended Posts

Wavarian    850
This just came apparent to me, and as it has never happened before, I'd like to see if anyone knows what's up with it. typedef struct{ short width; } TSA; sizeof(TSA) = 2 typedef struct{ short width; short height; } TSAB; sizeof(TSAB) = 4 but.. typedef struct{ short width; short height; unsigned char bpp; } TSABC; sizeof(TSABC) = 6 It seems as if a byte type-identifier is being appended to the TS, and it is making things very difficult when reading/writing to files. It's the same result in release mode as in debug mode, what is causing this, and if possible, how can I fix it? Thanks =) [edited by - wavarian on May 27, 2004 3:52:45 AM]

Share this post


Link to post
Share on other sites
fagiano    307
That''s because C/C++ compilers align data to a certain datasize size(speed reason). looks like your is set to 2 bytes.

For instance:

struct {
short x;
char y;
short z;
}

for the compiler becomes

struct {
short x;
char y;
char __padding_added_by_compiler;
short z;
}



I don''t know which compiler you are using but look for "packing alignment" or "structure alignment".
set the packing to 1 byte will work as you were expecting.
however IMHO relying on structure packing is a bit dangerous, if you are passing the same struct between DLLs. You forget to set the same packing in each DLL, is gonna be fun to find out why wierd stuff starts happening.

ciao
Alberto

-----------------------------
The programming language Squirrel
http://squirrel.sourceforge.net

Share this post


Link to post
Share on other sites
the Speed Bump    240
The compiler reserves the right to tack a few ''filler'' bytes on the end (and/or in the middle of) structs to make them a nice convenient size for the hardware.

Look up ''#pragma pack'' if you really really need it to not do this.

"Without deviation, progress itself is impossible." -- Frank Zappa

Share this post


Link to post
Share on other sites
JohnBolton    1372
Structs are "padded" with empty bytes to ensure that their members are aligned properly in memory. Since the first member is a 2-byte value, it needs to be located at an even address (presumably according to the compiler options). The extra byte is added so that the second element of an array would start on an even address rather than an odd address.
Padding is also added between member variables for the same reason.


John Bolton
Page 44 Studios
Current project: NHL Faceoff 2005 PS2

Share this post


Link to post
Share on other sites
Wavarian    850
Thanks alot for all your help, I''m only using tstructs to make reading a chunk of data from files more organized, so I doubt it''ll lead to any more problems.

Thanks again.

Share this post


Link to post
Share on other sites