C - 字段类型不完整

use*_*812 8 c struct

在下面的表示中,

struct Cat{
  char *name;
  struct Cat mother;
  struct Cat *children;
};
Run Code Online (Sandbox Code Playgroud)

编译器为第二个字段提供以下错误,但不是第三个字段,

 error: field ‘mother’ has incomplete type
   struct Cat mother;
              ^
Run Code Online (Sandbox Code Playgroud)

如何理解这个错误?

Sto*_*ica 13

该错误意味着您尝试将成员添加到struct尚未完全定义的类型中,因此编译器无法知道其大小以确定对象布局.

在您的特定情况下,您尝试struct Cat将自己的完整对象作为成员(mother字段).类型定义中的那种无限递归当然是不可能的.

然而,结构可以包含指向其他实例的指针.因此,如果您按如下方式更改定义,则它将是有效的struct:

struct Cat{
  char *name;
  struct Cat *mother;
  struct Cat *children;
};
Run Code Online (Sandbox Code Playgroud)