代码之家  ›  专栏  ›  技术社区  ›  Vinit Dhatrak

C中空结构的大小是多少?

  •  26
  • Vinit Dhatrak  · 技术社区  · 16 年前

    在我看来,它是零,但似乎有点混乱 here

    我用gcc编译器测试了它,它的输出为零。我知道在C++中,空类的大小是1。如果我遗漏了什么,请告诉我。

    4 回复  |  直到 6 年前
        1
  •  41
  •   Johannes Schaub - litb    16 年前

    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 { };
    

    它会给你一个诊断消息,因为你违反了语法规则。如果你写

    struct identifier { int : 0; };
    

    然后,你有一个没有命名成员的非空结构,因此行为未定义,不需要诊断:

    struct identifier { type ident[]; };
    
        2
  •  6
  •   Michael Burr    16 年前

    struct 为空-必须至少有一个未命名的位字段或一个命名的成员(就语法而言-我不确定只包含未命名位字段的结构是否有效)。

    Support for empty structs in C are an extension in GCC .

        3
  •  5
  •   Jerry Coffin    16 年前

    在C99中:“如果结构声明列表不包含命名成员,则行为未定义。”

        4
  •  1
  •   deven    13 年前

    在VC 8上,如果我们尝试获取sizeof空结构体,它会出错,而在linux上使用gcc时,它会给出size 1,因为它使用gcc扩展而不是c语言规范,c语言规范说这是未定义的行为。

    struct node
    {
    // empty struct.
    };
    
    int main()
    {
    printf("%d", sizeof(struct node));
    return 0;
    }
    

    在windows vc 2005上,出现了编译错误 http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Empty-Structures.html#Empty-Structures (正如Michael Burr所指出的那样)