struct的对齐不能与#pragma pack一起使用 [英] Alignment of struct didn't work with #pragma pack

查看:172
本文介绍了struct的对齐不能与#pragma pack一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个c ++结构:

I have a c++ structure:

struct a
{
     char b;
     int c;
     int d[100];
};

结构体的大小应为405字节。
我看到结构的大小是408字节。原因是在整数c后8个字节对齐。数组d应该从结构体的第6个字节开始,而不是第9个字节。
我使用 #pragma pack(1)但它没有解决问题。
我不能改变结构中字段的顺序。
你有什么想法如何解决这个问题?
谢谢!

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!

推荐答案

我使用的大多数编译器的错误包装是对象按照自己的大小排列。你的结构体的默认包装将在char之后和第一个int之前插入填充,以将该int放在4字节的边界上。显然这是你看到的行为。

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.

我在Visual Studio上使用的代码实现这样的包装。

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)

它删除了填充,将字节1 。

It removes the padding, aligning the int on byte 1.

如果我有一些时间,我会检查它的几个版本的VS来确认,但我现在的代码工作原理如下。这是怎么做的,所以唯一的问题是为什么它不为你工作。

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.

编辑:sizeof(a)是405如预期。 b的偏移量为1. VS2012。 Gcc是相同的。

sizeof(a) is 405 as expected. Offset of b is 1. VS2012. Gcc is the same.

这篇关于struct的对齐不能与#pragma pack一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆