View Full Version : Sturcture size
Questions Burner
12-11-2001, 12:36 AM
Let say I have a structure like
struct
{
char ch1;
char ch2;
};
The sizeof() the structure is 2 but when...
struct
{
char ch;
int num;
};
The sizeof() the structure is not
sizeof(char) + sizeof(num),
it's sizeof(int) * 2 ??!!
I just hate this because I can't directly read image file header, I have to read the value one by one.
1. This is offtoppic (i hate guys saying this http://www.opengl.org/discussion_boards/ubb/smile.gif )
2. That is because your compiler optimises the code for speed, so it aligns your data to 4byte blocks...
3. solving your problem (dirt way, i think):
struct{
char dummy[3];//this space is unused like in your code
char ch;
int num
} x;
//by reading data you have to correct the pointer:
char *ptr= (char *)&x + 3;
[This message has been edited by T2k (edited 12-11-2001).]
DFrey
12-11-2001, 04:59 AM
Another option is to use a pragma to disable the alignment optimization for that structure.
Questions Burner
12-11-2001, 08:24 PM
Thanks for T2K's "dirty" method. But I prefer just to disable it, but how??
This is for MSVC. Might work for other compiler aswell.
#pragma pack(push, 1)
// your structure goes here
#pragma pack(pop)
1 after the push means one byte alignment.
You can of course define as many structures as you want inside the pack-block.
Questions Burner
12-12-2001, 07:14 PM
What's the differences between
#pragma pack(1)
//...
and
What's the differences between
#pragma pack(1)
//structure
and
#pragma pack(push, 1)
//structure
#pragma pack(pop)
Originally posted by Questions Burner:
What's the differences between
#pragma pack(1)
//...
and
What's the differences between
#pragma pack(1)
//structure
and
#pragma pack(push, 1)
//structure
#pragma pack(pop)
The latter version will revert to the previously used pack method (=nice), whereas the former will leave it at 1 (=not so nice), which is not what subsequent code may expect.
HTH
Jean-Marc
Questions Burner
12-13-2001, 04:31 AM
Understood. http://www.opengl.org/discussion_boards/ubb/smile.gif
Powered by vBulletin® Version 4.2.0 Copyright © 2013 vBulletin Solutions, Inc. All rights reserved.