A structs contents is not only what you see visibly -- that's the point. The contents of the struct include padding bytes which you can't see or predict by just looking at a struct declaration.
Regards,
Paul McKenzie
Printable View
My mistake, I thought the compiler would shift items to word align them in C++ :/
Thanks Paul. You cleared my doubt. But is there any trick to guess struct size.
sizeof() as been suggested many times.
You can use this rule of thumb though. Take the number of bytes you expect it to be, and round up to the next multiple of four. That's usually a pretty good guess, but it's only a guess. No promises.
You should never ever require the size of it (one exception I can think of,) because programmatically, you will use sizeof() and things like array indexing and offsets are calculated automatically (and at compile time of course)
Yes if I need to know this programmatically then sizeof is okay.
but if this qus is asked me in some written exam ?. actually the main posted qus is taken from some interview qus series.
The correct answer on a written exam would be to state that the struct size is dependent on compiler choice and compile options. If you wish you can state one possible size by rounding every field's size up to the nearest multiple of 4 and then adding, but be clear that's just a possibility, not a certain size.
If the question asks about pragma pack, then you can specify an exact size by using the alignment rules laid out here:
http://msdn.microsoft.com/en-us/libr...8VS.80%29.aspx
I don't think this is correct.
Should be 4 bytes on most platforms (is on OSX with GCC.) You actually want to add them all up first, then round. Not sure if you just mistyped or not, but thought I would clear it up for the OP. But again, this is a guess at the size.Code:struct foo {
short i;
short j;
};
I imagine when getting into unions or bit fields the rules start getting really weird.