Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Field has incomplete type [duplicate]

Tags:

c

struct

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?

like image 517
user1787812 Avatar asked Jan 28 '17 21:01

user1787812


People also ask

Does C have incomplete type?

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).

What is an incomplete type?

An incomplete type is a type that describes an identifier but lacks information needed to determine the size of the identifier. An incomplete type can be: A structure type whose members you have not yet specified. A union type whose members you have not yet specified.


1 Answers

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;
};
like image 76
StoryTeller - Unslander Monica Avatar answered Oct 03 '22 04:10

StoryTeller - Unslander Monica