-2

I have the folowing header file :

 #ifndef SERVER_STRUCTURES_H
 #define SERVER_STRUCTURES_H

typedef struct game {
  int id;
  struct player player1;
  struct player player2;
  struct game *next;
} game_t;

typedef struct player {
  int id;
  int score;
  struct player *player1;
  struct game *g ;
} player_t;

#endif

I get the error: field 'player1' has incomplete type struct player player1

and

field 'player2' has incomplete type struct player player2.

What is the mistake? thank you!

irinao
  • 11
  • 6
  • Possible duplicate of [Structs that refer to each other](https://stackoverflow.com/questions/4394079/structs-that-refer-to-each-other) – MrTux Nov 10 '19 at 09:44
  • `struct player` is an incomplete type from the beginning until the closed brace of its definition. You cannot declare a variable or a struct field of an incomplete type. That's the mistake. – n. m. could be an AI Nov 10 '19 at 09:45
  • Pick your text-book and search for the term *forward declaration*. And think about the order in which you define things. – Some programmer dude Nov 10 '19 at 09:49

1 Answers1

1

Declarations must be before where they are used, so the two declarations should be swapped. To allocate player1 and player2, the compiler will require the full declaration of struct player.

Then, you should tell the compiler that struct game will be declared later. It is enough information to create "pointer to something".

#ifndef SERVER_STRUCTURES_H
#define SERVER_STRUCTURES_H

struct game;

typedef struct player {
  int id;
  int score;
  struct player *player1;
  struct game *g ;
} player_t;

typedef struct game {
  int id;
  struct player player1;
  struct player player2;
  struct game *next;
} game_t;

#endif
MikeCAT
  • 73,922
  • 11
  • 45
  • 70