Visual C ++ offers both a compiler switch ( /Zp
) and a pragma pack
to affect the aligment of structure members. However, I seem to have a misconception about how they work.
According to MSDN for the given alignment value n,
The alignment of the element will be on the border, which is either a multiple of n or a multiple of the size of the member, whichever is smaller.
Assume the packet value is 8 bytes (which is the default value). Inside the structure, I think that any member whose size is less than 8 bytes will have an offset multiple of its size. Any member that is 8 bytes or more in size will have an offset multiple of 8 bytes.
Now take the following program:
#include <tchar.h> #pragma pack(8) struct Foo { int i1; int i2; char c; }; struct Bar { char c; Foo foo; }; int _tmain(int argc, _TCHAR* argv[]) { int fooSize = sizeof(Foo); // yields 12 Bar bar; int fooOffset = ((int) &bar.foo) - ((int) &bar); // yields 4 return 0; }
The Foo
structure is 12 bytes in size. So, in Bar
I would expect the Foo
member to be at offset 8 (a multiple of 8), while in reality it is at offset 4. Why is this?
In addition, Foo
really only has 4 + 4 + 1 = 9 bytes of data. The compiler automatically adds padding bytes at the end. But then again, given the alignment value of 8 bytes, shouldn't it be cast to a multiple of 8, not 4?
Any clarifications are appreciated!
source share