Question

I'm working with graphs. I have a problem with pointers when I want to insert an edge in a list of edges.

This is all the graph structure:

typedef struct _edge {
  int source;         
  int dest;          
  int cost;          
  struct _edge *next; 
} edge;

typedef struct {
  int  id;       
  rama *edges;   /* List of edges */
} node;

typedef struct {  
  int n_nodes;     
  int n_edges;     
  int directed;    
  node *nodes;  /* Array of nodes */
} graph;

My problem comes when I try to insert a new edge in the list of edges...

int insert_edge(graph *g, int source, int dest, int cost){

    edge *e;
    edge *nxt;

    e=(edge*)malloc(sizeof(edge));
    e->source=source;
    e->dest=dest;
    e->cost=cost;
    e->next=NULL;

    nxt=g->nodes[source].edges;
    if(nxt==NULL)
        nxt=e;  
    else
    {   
        while(nxt->next!=NULL)  
            nxt=nxt->next;  
        nxt->next=e;        
    }       
    return 1;
}

When I call my insert_edge from a main function I have a segmentation fault when I try to access the fields of the edges.

How can I make the insertions correctly?

When I access my graph->nodes[position].edges it's still null... I don't know how to update the content of the graph inside my insert function.

Was it helpful?

Solution

        nxt=nxt>next; 

This typo basically makes you assign 0/1 to nxt, and later you treat it like a pointer.

(PS I am almost certain compiler provided warning for it that could save your valuable time).


One more issue is with nxt=e; instead of g->nodes[source].edges = e.
In the first - you merely change the local variable, but don't actually change the data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top