gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:15:09 25 4
gpt4 key购买 nike

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com