简体   繁体   中英

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?

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 .

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM