问题
I have a c++ structure:
struct a
{
char b;
int c;
int d[100];
};
The size of the struct should be 405 bytes.
I saw that the size of the struct is 408 bytes. The reason is the alignment to 8 bytes after the integer "c". The array "d" should start at the 6th byte of the struct and not at the 9th byte.
I used #pragma pack(1)
but it didn't solve the problem.
I cannot change the order of fields in the struct.
Do you have any idea how can I solve this problem?
Thanks!
回答1:
The fault packing for most compilers I use is that objects align on their own size. The default packing for your struct would insert padding after the char and before the first int, to place that int on a 4 byte boundary. Obviously this is the behaviour you are seeing.
The code I use on Visual Studio to achieve packing looks like this.
#pragma pack(push,1)
struct a {
char b;
int c;
int d[100];
};
#pragma pack(pop)
It removes the padding, aligning the int on byte 1.
If I get some time I'll check it on a couple of versions of VS to confirm that, but my current code works exactly like this. This is how it's done, so the only question is why it isn't working for you.
EDIT: sizeof(a) is 405 as expected. Offset of b is 1. VS2012. Gcc is the same.
来源:https://stackoverflow.com/questions/22112171/alignment-of-struct-didnt-work-with-pragma-pack