Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to declare 2 structs contain each other in c

I am implementing a graph structure for a maze solving program. I declare 2 structs: vertex contains label to label that vertex, 4 directions of edge; edge contains weight and a vertex pointer to 4 other vertices.

extern struct graph
{
    int label;
    struct Edge up;
    struct Edge down;
    struct Edge left;
    struct Edge right;
}vertex;

extern struct Edge
{
    int weight;
    struct graph *neighbour;
}edge;

typedef struct graph vertex;
typedef struct Edge edge;

This way of declaration leads to some errors: unknown type name ‘vertex’; field ‘up’ has incomplete type,..

(I have tried to us extern but it doesn’t seem to be the problem).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So how do I declare it properly?

Any help would be appreciated.

>Solution :

Not sure why a graph is also a Vertex, but you can reverse the order you declare the 2 structs and use a forward declaration. You can also combine the struct declarations and the typedefs.

struct graph;  // Forward declaration

typedef struct 
{
    int weight;
    graph *neighbour;
} edge;

typedef struct graph 
{
    int label;
    edge up;
    edge down;
    edge left;
    edge right;
} graph;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading