MaxDevelop
MaxDevelop

Reputation: 637

two structs containing each other

I have this code:

typedef struct
{
    node* dest;
} edge;

typedef struct
{
    char *name;
    int visited;
    edge* edges[MAX_E];
} node;

So now struct edge have node*, and struct node have edge*, any one can explain to me how this work?

Upvotes: 2

Views: 104

Answers (3)

Tom Karzes
Tom Karzes

Reputation: 24052

I prefer to do it this way:

typedef struct node_s node;
typedef struct edge_s edge;

struct edge_s
{
    node   *dest;
};

struct node_s
{
    char   *name;
    int     visited;
    edge   *edges[MAX_E];
};

That way you can use the typedef names everywhere.

Note that neither struct contains an instance of the other. Instead, they each contain pointers to the other. So the dependency is just a matter of being able to access pointers to the types before they've been defined.

Upvotes: 2

pmg
pmg

Reputation: 108968

You need to declare (not define) one of the structs first

struct edge; // declare struct

struct node {
    char *name;
    int visited;
    struct edge *edges[MAX_E]; // array pf pointers
};
struct edge {
    struct node *dest;
};

Of course you can use typedef here. But I fail to see any advantage in using it, so my code stays clear of typedef.

Upvotes: 2

Tom's
Tom's

Reputation: 2506

Well, it's can't compile rigth away due to cross-definition of the structure. You can fix that by adding the definition of the second structure before the first (like an opaque structure).

struct node;

Don't forgot to name your structure for that.

After that, it will do exactly what it was coded for : edge->dest is a "node" pointer and "node" have an egde pointer array.

Upvotes: 0

Related Questions