Search code examples
cstructdouble-pointer

double pointer to struct inside struct


How can i access to a duble pointer in a struct pointer?? with the code bellow, calling addBow() give me a Segmentation fault (core dumped) error

typedef struct
{
    int size;
    tCity **cities;

}tGraph;

//para iniciar el grafo
void initGraph(tGraph *graph, int size)
{
    graph = (tGraph*)malloc(sizeof(tGraph));
    graph->cities = (tCity**)malloc(sizeof(tCity*) * size);
    graph->size = size;
}

//agrega un arco entre ciudades
void addBow(tGraph *graph, int id, tCity *city)
{
    if ( graph->cities[id] == NULL ) 
    {    
        graph->cities[id] = city;
    }
    else
    {
        tCity *cur = graph->cities[id];
        while ( getNext(cur) != NULL ) 
        {
            cur = getNext(cur);
        }
        setNext(cur, city);
    }
}    

which is the correct syntax for graph->cities[id]??

Thanks

SOLUTION: editing the initGraph solve the problem since the memory wasn't allocated

tGraph* initGraph(int size)
{
    tGraph *graph = (tGraph*)malloc(sizeof(tGraph));
    graph->cities = (tCity**)malloc(sizeof(tCity*) * size);
    graph->size = size;
    return graph;
}

Solution

  • You should either have initGraph() take (**graph) or return the graph. Since the malloc address of graph is local to initGraph.

    Something like:

    void initGraph(tGraph **graph, int size)
    {
        tgraph *temp;
        temp = (tGraph*)malloc(sizeof(tGraph*));
        temp->cities = (tCity**)malloc(sizeof(tCity*) * size);
        temp->size = size;
        *graph = temp;
    }