c - 结构中的位域概念

标签 c struct bit-fields

#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/

相关文章:

.net - 我在哪里可以找到 CorFlags 值的每一位含义的引用?

c - 为 Windows 编写正确的 Ansi C makefile

c - I2C & SPI 开机自检

c - 在没有赋值的情况下初始化结构?

c - 关系数据库和查询

python - 基于位域创建字符串

c - 尝试交换用户输入数组中的多个值

python - 如何在mac上将C的 bool 值更改为python的 bool 值

C 结构返回指针,存储在引用中

c++ - 线程安全和位域