结构混乱

Structure Confusion

我已经有一段时间没有接触 C 语言了,所以我只是了解了一些概念,但找不到任何关于结构的好资料。

谁能解释一下

struct A
{
   int a;
   char b;
   float c;
};

这是结构体的声明还是定义A.

这是一个声明。

struct A;forward declaration 或不完整的声明。

struct A
{
   int a;
   char b;
   float c;
};

完成struct声明。

Example

同时勾选 comp.lang.c FAQ list Question 11.5

struct 的前向声明之后,您可以使用结构指针但不能解引用指针或使用 sizeof 运算符或创建 struct.

的实例

声明后,还可以使用struct对象,应用sizeof运算符等


来自 6.7.2.1 结构和联合说明符 来自 C11 规范

8 The type is incomplete until immediately after the } that terminates the list, and complete thereafter.

来自 6.7.2.3 标签

If a type specifier of the form
struct-or-union identifier occurs other than as part of one of the above forms, and no other declaration of the identifier as a tag is visible, then it declares an incomplete structure or union type, and declares the identifier as the tag of that type.131)
131A similar construction with enum does not exist


这不应与 extern struct A aa; v/s struct A aa ={/*Some values*/}; 混淆,后者是对象 aa.

的声明和定义

它使用结构标记 A 和指定的成员声明了一个结构。它既不定义也不保留对象的任何存储空间。

来自 C99 标准,6.7 声明:

Semantics

5 A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that:

— for an object, causes storage to be reserved for that object;

— for a function, includes the function body; (footnote 98)

— for an enumeration constant or typedef name, is the (only) declaration of the identifier.

对于定义,您需要在最后一个分号之前提供一个对象标识符:

struct A
{
   int a;
   char b;
   float c;
} mystruct;

要同时初始化 mystruct,您可以编写

struct A
{
   int a;
   char b;
   float c;
} mystruct = { 42, 'x', 3.14 };