c - 为什么 sizeof 未命名位域成员结构打印 1?

标签 c structure sizeof bit-fields

在下面的程序中,在结构中声明了未命名的位域成员。

#include <stdio.h>

struct st{
    int : 1;
};

int main()
{
    struct st s;
    printf("%zu\n",sizeof(s));  // print 1
}

以上程序打印输出1。

为什么 sizeof(s) 打印 1

最佳答案

sizeof(s)undefined因为结构中没有其他命名成员。

C11 6.7.2.1(P8):

The presence of a struct-declaration-list in a struct-or-union-specifier declares a new type, within a translation unit. The struct-declaration-list is a sequence of declarations for the members of the structure or union. If the struct-declaration-list contains no named members, no anonymous structures, and no anonymous unions, the behavior is undefined. The type is incomplete until immediately after the } that terminates the list, and complete thereafter.

如果你这样写:

struct st{
        int : 1;
        int i : 5;
    };

所以,sizeof(s) 是可以的,因为结构中也有命名的位域成员。

关于c - 为什么 sizeof 未命名位域成员结构打印 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47461255/

相关文章:

c++ - 如何在 C 和 C++ 中实现装饰器

c - 这两种写结构的方式有什么区别?

c++ - 这个结构怎么会有 sizeof == 0?

c++ - 为什么 std::string 上的 Sizeof 运算符会产生意外结果?

c++ - 嵌套在模板类中的类的大小,但不依赖于模板参数

c - 分配字符数组和字符串

c++ - 如何更新项目中的所有 C/C++ 标识符名称

c - 如何将全局值从 C 传递到 LUA?

mysql - 比较两个数据库的结构?

algorithm - 带有 prim 的堆结构