C 中的位域,其结构包含结构体的并集
嗯...为什么当我打印 sizeof(struct MyStruct)
时,这段代码会输出 3(而不是 2)?
#pragma pack(push, 1)
struct MyStruct
{
unsigned char a : 6;
union
{
struct
{
unsigned int b : 9;
};
};
};
#pragma pack(pop)
万一重要的话,我在 Windows 7 x64 上运行 MinGW GCC 4.5.0,但老实说,结果对我来说很奇怪,我认为编译器和操作系统在这里并不重要。 :\
Hm... why is it that, when I print sizeof(struct MyStruct)
, it outputs 3 (instead of 2) for this code?
#pragma pack(push, 1)
struct MyStruct
{
unsigned char a : 6;
union
{
struct
{
unsigned int b : 9;
};
};
};
#pragma pack(pop)
In case it matters, I'm running MinGW GCC 4.5.0 on Windows 7 x64, but honestly, the result is weird enough for me that I don't think the compiler and the OS matter too much here. :\
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
字段不能从非字节对齐的地址开始。
您期望:
但您得到的是:
数据存储为:
当您期望时:
编辑:
根据以下注释进行澄清:
联合(和包含的结构)必须是字节对齐的。内容只有 9 位并不重要,union/struct 本身就是完整的 16 位。请注意,您不能执行以下操作:
因为 C 不允许您指定整个结构的位大小。
You can't have the field starting at an address that is not byte aligned.
You're expecting:
but what you're getting is:
The data is being stored as:
when you were expecting:
edit:
To clarify based on the comments below:
The union (and the containing struct) must be byte aligned. It doesn't matter that the contents are only 9 bits, the union/struct itself is a full 16 bits. Notice that you cannot do the following:
As C won't let you specify the entire struct's bit-size.
添加@nss给出的答案——我很抱歉,如果评论在格式上没有如此限制的话,这将是一条评论:
它打印“4”的大小。我用 gcc、g++ 和 Sun Studio 的 CC 和 cc 进行了测试。
我并不是建议您做您正在尝试做的事情,但您可能可以通过工会做您正在尝试做的事情。我见过(但不是我自己写的)代码,看起来像这样:
我的语法可能略有错误......但我不这么认为。
要点是:使用您想要的布局创建两个单独的结构(或结构和联合),然后在它们应该重叠的位置插入一些虚拟成员,并将它们联合在一起。
Adding to the answer given by @nss -- my apologies, this would've been a comment if comments weren't so limited on formatting:
It prints '4' for the size. I tested with gcc, g++, and Sun Studio's CC and cc.
Not that I recommend doing what you're attempting to do, but you could probably do what you're attempting to do with a union. I've seen (but not written myself) code that looked like this:
I might have the syntax slightly wrong there ... but I don't think so.
Point being: create two separate structs (or a struct and a union) with the layout you were going for, then insert some dummy members where they should overlap, and union those together.