Vega Vega - 1 month ago 12
C Question

How to use an struct inside a struct

Today my programming teacher given us a challenge to resolve.

We have two structs but each one is using the another struct like this:

typedef struct nodeA {
int data;
NODE_B *node_b;
struct nodeA *next;
} NODE_A;

typedef struct nodeB {
int data;
NODE_A *node_A;
struct nodeB *next;
} NODE_B;


Of course the order of de declarations every time give a "NODE_X type non-declared" error.

Is there any way for resolve this?

I don't know if exists the prototype for structs like:

typedef struct NODE_A;

jxh jxh
Answer

It is probably easiest to forward declare both typedefs:

typedef struct nodeA NODE_A;
typedef struct nodeB NODE_B;

struct nodeA {
    int data;
    NODE_B *node_b;
    NODE_A *next;
};

struct nodeB {
    int data;
    NODE_A *node_A;
    NODE_B *next;
};