PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, June 27, 2022

[FIXED] How to declare 2 structs contain each other in c

 June 27, 2022     c, graph, struct     No comments   

Issue

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).

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;
    struct graph *neighbour;
} edge;

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


Answered By - Johnny Mopp
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing