问题描述
我正在使用linux上的c结构。
我开始使用位字段和packed属性,并且遇到了一个奇怪的行为:
$ $ $ $ $ $ $ $ $ struct $
{
int a:12;
int b:32;
int c:4;
} __属性__((packed));
struct t2
{
int a:12;
int b;
int c:4;
} __属性__((packed));
void main()
{
printf(%d\\\
,sizeof(t1)); //输出 - 6
printf(%d \ n,sizeof(t2)); //输出 - 7
}
两个结构如何 - 完全相同 - 需要不同的字节数?
您的结构不是完全相同。你的第一个有三个连续的位域,第二个有一个位域,一个(非位域)int,然后是第二个位域。
这是有意义的:连续(非零宽度)位字段合并到单个存储位置中,而位字段后跟非位字段是不同的存储位置。 >您的第一个结构有一个内存位置,第二个结构有三个。您可以在第二个结构中取得 b
成员的地址,而不是第一个结构中的地址。对 b
成员的访问不会与访问 a
或 c
在你的第二个结构中,但它们在你的第一个结构中。
紧接着有一个非位字段(或一个零长度的位字段)一个位域成员在一个敏感中关闭它,接下来将是一个不同的/独立的内存位置/对象。编译器无法像在第一个结构中一样打包您的 b
成员。
I am working with structs in c on linux.I started using bit fields and the "packed" attribute and I came across a wierd behavior:
struct t1
{
int a:12;
int b:32;
int c:4;
}__attribute__((packed));
struct t2
{
int a:12;
int b;
int c:4;
}__attribute__((packed));
void main()
{
printf("%d\n",sizeof(t1)); //output - 6
printf("%d\n",sizeof(t2)); //output - 7
}
How come both structures - that are exactly the same - take diffrent number of bytes?
Your structures are not "exactly the same". Your first one has three consecutive bit-fields, the second has one bit-field, an (non bit-field) int, and then a second bit-field.
This is significant: consecutive (non-zero width) bit-fields are merged into a single memory location, while a bit-field followed by a non-bit-field are distinct memory locations.
Your first structure has a single memory location, your second has three. You can take the address of the b
member in your second struct, not in your first. Accesses to the b
member don't race with accesses the a
or c
in your second struct, but they do in your first.
Having a non-bit-field (or a zero-length bit-field) right after a bit-field member "closes" it in a sens, what follow will be a different/independent memory location/object. The compiler cannot "pack" your b
member inside the bit-field like it does in the first struct.
这篇关于C结构中的压缩位字段 - GCC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!