什么是用C空结构的大小? [英] What is the size of an empty struct in C?
问题描述
据我来说,这是零,但似乎有一点混乱<一个href=\"http://stackoverflow.com/questions/1626017/why-sizeofspinlockt-is-greater-than-zero-on-uni-processor/1626054#1626054\">here
According to me, it is zero but there seems to be bit confusion here
我与gcc编译器测试,它给了我零输出。我知道,在C ++中,空类的大小为1。让我知道如果我在这里缺少什么。
I have tested it with gcc compiler and it gives me zero as output. I know that in C++, size of an empty class is 1. Let me know if I am missing anything here.
推荐答案
因为语法禁止它结构不能在C空。此外,还有一种语义约束,使得不确定的行为,如果一个结构没有命名的成员:
A struct cannot be empty in C because the syntax forbids it. Furthermore, there is a semantic constraint that makes behavior undefined if a struct has no named member:
struct-or-union-specifier:
struct-or-union identifieropt { struct-declaration-list }
struct-or-union identifier
struct-or-union:
struct
union
struct-declaration-list:
struct-declaration
struct-declaration-list struct-declaration
struct-declaration:
specifier-qualifier-list struct-declarator-list ;
/* type-specifier or qualifier required here! */
specifier-qualifier-list:
type-specifier specifier-qualifier-listopt
type-qualifier specifier-qualifier-listopt
struct-declarator-list:
struct-declarator
struct-declarator-list , struct-declarator
struct-declarator:
declarator
declaratoropt : constant-expression
如果你写
struct identifier { };
这会给你一个诊断信息,因为你违反语法规则。如果你写
It will give you a diagnostic message, because you violate syntactic rules. If you write
struct identifier { int : 0; };
那么你有没有命名的成员非空的结构,从而使行为的定义,而不是要求一个诊断:
Then you have a non-empty struct with no named members, thus making behavior undefined, and not requiring a diagnostic:
如果在结构声明列表中没有名称的成员,其行为定义理解过程网络。
If the struct-declaration-list contains no named members, the behavior is undefined.
请注意,以下是不允许的,因为灵活的阵列成员不能成为第一个成员:
Notice that the following is disallowed because a flexible array member cannot be the first member:
struct identifier { type ident[]; };
这篇关于什么是用C空结构的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!