在下面的程序中,在结构中声明了未命名的位域成员。
#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/