1

構造体ポインターの二重ポインターにアクセスするにはどうすればよいですか?? 以下のコードで addBow() を呼び出すと、Segmentation fault (core dumped) エラーが発生します

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

graph->cities[id] の正しい構文はどれですか??

ありがとう

解決策: メモリが割り当てられていないため、initGraph を編集すると問題が解決します

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

4 に答える 4

1

initGraph() で (**graph) を取得するか、グラフを返す必要があります。グラフの malloc アドレスは initGraph に対してローカルであるためです。

何かのようなもの:

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;
}
于 2013-08-31T22:03:12.247 に答える
1

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

あなたの問題の1つがあります...それはあるべきです graph = malloc(sizeof(tGraph));

于 2013-08-31T22:05:07.270 に答える
0

へのポインターをinitGraph ()返すようにしますtGraph

tGraph* initGraph(int size) {

tGraph* graph;

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

return graph;
}
于 2013-08-31T22:40:48.910 に答える