Alignment of struct didn't work with #pragma pack

99封情书 提交于 2019-12-30 11:34:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!