struct zirkulär definiert



  • Hallo,

    ich habe ein Problem mit der Definition von structs. Ich möchte Knoten (node) und Kanten (edge) eines Graphen effizient abbilden. Also:

    // an edge
    typedef struct {
    	node* targetNode; // pointer to the target node
    	int cost;	// the cost of travelling along this edge
    
    } edge;
    
    typedef struct {
    	char id[NODE_ID_SIZE]; /* the id of this node */
    	char name[100]; /* the name of this node */
    	edge edges[MAX_EDGES_PER_NODE];
    } node;
    

    Auf gut deutsch, der Knoten hat alle Kanten, die von ihm weg führen in einem Array edges. Jede edge wiederum hat einen Pointer auf ihren Zielknoten in targetNode.
    Allerdings kann ich diesen Code nicht kompilieren, denn beim ersten Auftauchen von node in edge ist node dem Compiler natürlich noch nicht bekannt.
    Wie kann ich das auflösen????

    Dank im voraus



  • Forward Declaration:

    struct node;
    
    struct edge
    { 
        struct node* targetNode; // pointer to the target node 
        int cost;    // the cost of travelling along this edge 
    
    }; 
    
    struct node
    { 
        char id[NODE_ID_SIZE]; /* the id of this node */ 
        char name[100]; /* the name of this node */ 
        struct edge edges[MAX_EDGES_PER_NODE]; 
    };
    

    Ich weiß jetzt aber nicht, wie das mit dem typedef aussieht, also wie man dann "struct node;" benutzen muss. Noch nie gemacht und bin gerade zu faul es zu testen >:D

    Edit:

    Sowas geht natürlich auch, also auf typedef musst du nicht verzichten:

    struct node_s;
    
    typedef struct edge_s
    { 
        struct node_s* targetNode; // pointer to the target node 
        int cost;    // the cost of travelling along this edge 
    
    } edge; 
    
    typedef struct node_s
    { 
        char id[NODE_ID_SIZE]; /* the id of this node */ 
        char name[100]; /* the name of this node */ 
        struct edge_s edges[MAX_EDGES_PER_NODE]; 
    } node;
    

    Ich weiß nur nicht, ob sowas wie

    struct node;
    
    typedef struct
    { 
        struct node* targetNode; // pointer to the target node 
        int cost;    // the cost of travelling along this edge 
    
    } edge; 
    
    typedef struct
    { 
        char id[NODE_ID_SIZE]; /* the id of this node */ 
        char name[100]; /* the name of this node */ 
        struct edge edges[MAX_EDGES_PER_NODE]; 
    } node;
    

    funktioniert, wobei ich das bezweifele.



  • Prima, vielen Dank!


Anmelden zum Antworten