#include<stdio.h>
main()
{
union d
{
unsigned int a:1;
unsigned int b:3;
unsigned :0;
unsigned int d:1;
unsigned int e:1;
};
union d aa;
aa.b=9;
printf("d.aa.a=%d d.aa.b=%d",aa.a, aa.b);
system("pause");
}
在这个问题中,union 的大小将不同于为 union 分配的位字段的数量。任何人都可以解释差异..剩余的内存会发生什么?
最佳答案
关于包含位字段的类型的大小,标准说 (C11 6.7.2.1 p11):
An implementation may allocate any addressable storage unit large enough to hold a bit-field.
因为这是一个 union
,并且 union 中的所有成员只使用来自unsigned int
的不超过3位,的大小union
至少是 char
的大小,加上系统要求的填充(如果有)。在许多系统上,它会将每个单元填充到位字段所针对的类型的大小,因此在这种情况下,我希望 union
的大小与一个 unsigned int
(尽管这可能是由于正常的 union
填充要求而发生的)。
0
大小的位字段在 union
中是一个转移注意力的问题,但它在 struct
中具有特殊含义(C11 6.7 .2.1 p12):
A bit-field declaration with no declarator, but only a colon and a width, indicates an unnamed bit-field. As a special case, a bit-field structure member with a width of 0 indicates that no further bit-field is to be packed into the unit in which the previous bit-field, if any, was placed.
因此,如果您的 union
是一个 struct
:
struct d
{
unsigned int a:1;
unsigned int b:3;
unsigned :0;
unsigned int d:1;
unsigned int e:1;
};
那么这个struct
的大小将至少为2 个char
(如果需要,再加上任何其他填充)。大多数时候,它实际上会达到 2 个 unsigned int
的大小。
关于c - 位域和 union 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17733034/