#include<stdio.h>
int main()
{
struct value
{
int bit1:1;
int bit2:4;
int bit3:4;
}bit;
printf("%d\n",sizeof(bit));
}
我正在使用 GCC,它显示的 sizeof(bit)
值为 4。您能解释一下它的内部工作原理吗?
最佳答案
引用 C11
标准,第 §6.7.2.1
章,结构和 union 说明符,(强调我的)
implementation may allocate any addressable storage unit large enough to hold a bitfield. If enough space remains, a bit-field that immediately follows another bit-field in a structure shall be packed into adjacent bits of the same unit. If insufficient space remains, whether a bit-field that does not fit is put into the next unit or overlaps adjacent units is implementation-defined.....
就您而言,由于(第一个变量类型)int
大小足以将所有位字段变量打包到一个 int
中,因此它正在这样做。
因此,本质上您的 sizeof(bit)
等同于 sizeof(int)
,它可能会产生值 4
,单位为 32位系统。
也就是说,sizeof
生成一个size_t
类型的值。您应该使用 %zu
格式说明符来打印该值。
[由社区编辑添加]
案例1:
如果您使用如下所示的
char
,它将显示大小为1
,因为char
可以容纳 7 位。#include<stdio.h> int main(void) { struct value { char bit1:1; char bit2:2; char bit3:4; }bit; printf("%d\n",sizeof(bit)); }
案例2:
在下面的情况下,结果将为“2”,因为总共需要 2 个
char
来存储9
位。char bit1:1; char bit2:4; char bit3:4;
关于c - 结构中的位域概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31203265/