2

I defined a structure in a file.c and I defined a typedef to his pointer in his header. I want to use this typedef in another file.c but it doesnt work. I think that it is a problem with the include of the files.

In the file game.c

#include <stdbool.h>
#include <stdlib.h>

#include "chessSystem.h"
#include "tournament.h"
#include "game.h"
#include "map.h"
#include "player.h"

struct Game_node
{
    int game_id;
    Game_data game_data;
    Game next;
};

In the file game.h I am doing:

typedef struct Game_Node *Game;

And I want to use this struct in another file: tournament.c Into a function I try to define a variable of the type Game. But I cant access to the fields of the struct.

#include "game.h"
..........

Game temp_game=malloc(sizeof(*temp_game));
    temp_game->

Important to signal that in the allocation of temp_game the IDE signal an error:Invalid application of 'sizeof' to an incomplete type 'struct Game_node'.

I know that is not very clear. if you have questions tell me.

Thanks you so much.

  • 2
    Move the struct definition from the C file to the header file. – stark May 13 '21 at 20:03
  • 1
    Move the structure definition to the `.h` file where it belongs. If it's not in the `.h` file, then *of course* other files can't see it. Think about it. – Tom Karzes May 13 '21 at 20:03
  • 1
    See [Is it a good idea to typedef pointers?](https://stackoverflow.com/questions/750178/is-it-a-good-idea-to-typedef-pointers) — TL;DR the answer is usually "No", with possible exceptions for function pointers. – Jonathan Leffler May 13 '21 at 20:05

1 Answers1

0

The type definition typedef struct Game_Node *Game; refers to an incomplete type as the details of the structure Game_Node are not known. The compiler can still compile code that only uses pointers to struct Game_Node but not code that uses sizeof(struct Game_Node) or accesses members of this structure.

A common case is FILE often defined in <stdio.h> as an incomplete type. The various stream functions take a FILE * and user code does not need to know the details of the implementation, which varies a lot from on system to another.

You should move the structure definition from game.c to game.h.

If you want to restrict access to the structure internals, you could define it in a separate file gamedef.h only included in the appropriate modules.

chqrlie
  • 131,814
  • 10
  • 121
  • 189