21

In the below representation,

struct Cat{
  char *name;
  struct Cat mother;
  struct Cat *children;
};

Compiler gives below error for second field, but not third field,

 error: field ‘mother’ has incomplete type
   struct Cat mother;
              ^

How to understand this error?

user1787812
  • 433
  • 1
  • 5
  • 12

1 Answers1

22

The error means that you try and add a member to the struct of a type that isn't fully defined yet, so the compiler cannot know its size in order to determine the objects layout.

In you particular case, you try and have struct Cat hold a complete object of itself as a member (the mother field). That sort of infinite recursion in type definition is of course impossible.

Nevertheless, structures can contain pointers to other instances of themselves. So if you change your definition as follows, it will be a valid struct:

struct Cat{
  char *name;
  struct Cat *mother;
  struct Cat *children;
};
SolarBear
  • 4,534
  • 4
  • 37
  • 53
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458