-
Varying Struct Sizes
Odd. I have a struct like this:
Code:
struct Old {
int a;
char str[48];
int b;
int c;
int d;
};
and the sizeof() it is 64. Right. So I decided I needed to add a bool to it so I made the string 47 and added it, like so:
Code:
struct New {
int a;
char str[47];
int b;
int c;
int d;
bool x;
};
But the sizeof() the new struct is 68. Why? With the new struct it won't go back down to 64 until I decrease the size of str to 44.
I'm compiling with Borland and think there just must be some details about structs that I am unaware of. Have you any clue?
-
bools are not one byte. bools are 32 bits, therefore 4 bytes, therefore making the struct 68 bytes and not 64.
-
No they are not (depending on your compiler I suppose). A bool is 1 byte and a sizeof() confirms it. It's very odd because with the New struct, if the str size is 47, 46, or 45 the size of the struct is 68 (but it jumps down to 64 if the size of str is 44). There isn't a one-to-one relationship there for some reason.
-
Its really all about byte alignment.
Try changing it to:
Code:
struct New {
int a;
char str[47];
bool x;
int b;
int c;
int d;
};
And see what you get.
-
Brilliant. So, that is the reason... I have encountered this type of thing in the past but I just ignored it because it wasn't important.
Would you care to elaborate a little more on this little quirk?
Thanks. I see why you have such a good reputation.
-
It's just like he said, it has to do with data alginment. You can look it up and find information almost anywhere on the topic but it's not that interesting. If you are using MSVC you can change it by using
Code:
#pragma pack(push,1)
//.. structs
#pragma pack(pop)
That will force one-byte boundaries. You generally only need to worry about this sort of thing when you need a very small memory footprint. If you're using another compiler look up in the documentation to see if similar functionality exists.
-
Basically your cpu works more effiecently when it can uses address a certain way. Your compiler will try to do this as much as possible. The environment you are in wants things on even address.