1

I have this struct:

typedef struct {
    int id;
    node_t * otherNodes;
} node_t;

where I need an array of nodes in my node....

but in the header file is not recognized: it tell me `unknown type name 'node_t'

how can I solve this?

thanks

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
ghiboz
  • 7,863
  • 21
  • 85
  • 131
  • 1
    Does this answer your question? [self referential struct definition?](https://stackoverflow.com/questions/588623/self-referential-struct-definition) – kaylum Dec 12 '21 at 11:22
  • I'll try.. but I need an array of other nodes – ghiboz Dec 12 '21 at 11:24
  • 1
    The solution is to name the structure itself. Then you can *forward declare* the type-alias if you want. Or use the structure name when declaring the member. – Some programmer dude Dec 12 '21 at 11:26
  • You might want to read [comp.lang.c FAQ list - Question 1.14](http://c-faq.com/decl/selfrefstruct.html) – M. Nejat Aydin Dec 12 '21 at 11:44
  • 1
    Have you learned how to use a `struct` *without* using `typedef`? Because that would have probably prevented this issue. – Cheatah Dec 12 '21 at 11:44

2 Answers2

2

In this typedef declaration

typedef struct {
    int id;
    node_t * otherNodes;
} node_t;

the name node_t within the structure definition is an undeclared name. So the compiler will issue an error.

You need to write for example

typedef struct node_t {
    int id;
    struct node_t * otherNodes;
} node_t;

Or you could write

typedef struct node_t node_t;

struct node_t {
    int id;
    node_t * otherNodes;
};

Or even like

struct node_t typedef node_t;

struct node_t {
    int id;
    node_t * otherNodes;
};
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

I referenced defenition of struct list_head from kernel codes: https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/include/linux/types.h?h=v5.10.84#n178

So I would write like this:

struct node {
    int id;
    struct node * otherNodes;
};

typedef struct node node_t;