2013-08-31 86 views
0

我怎樣才能訪問一個結構指針雙指針? 與代碼波紋管,調用addBow()給我一個分段故障(核心轉儲)錯誤雙指針結構內結構

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->城市[ID]的正確語法??

感謝

SOLUTION: 編輯initGraph解決問題,因爲內存沒有被分配

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

回答

1

您應該有initGraph()取(**圖)或返回的圖形。由於圖的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; 
} 
+1

他在那裏存儲指針。 – Inspired

+0

@靈感。同意。更新了答案 –

+0

@ManojPandey Thaanks,解決它,更新。 – JoseMiguel

1

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

還有就是你的問題之一...... 應該 graph = malloc(sizeof(tGraph));

+2

這是一個問題,但我認爲崩潰現在是由'initGraph'將內存分配給調用者傳遞的指針副本引起的。即分配到一旦泄漏功能返回 – simonc

+0

@simonc良好的電話我沒有認識到這一點泄漏。 –

0

製作initGraph()返回一個指向tGraph

tGraph* initGraph(int size) { 

tGraph* graph; 

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

return graph; 
}