double pointer to struct inside struct

本秂侑毒 提交于 2020-01-15 11:45:08

问题


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;
}

回答1:


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;
}



回答2:


graph = (tGraph*)malloc(sizeof(tGraph*));

There is one of your problems... it should be graph = malloc(sizeof(tGraph));




回答3:


Make initGraph () return a pointer to tGraph.

tGraph* initGraph(int size) {

tGraph* graph;

graph = malloc(sizeof(tGraph));
graph->cities = malloc(sizeof(tCity*) * size);
graph->size = size;

return graph;
}


来源:https://stackoverflow.com/questions/18553181/double-pointer-to-struct-inside-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!