我必須根據某些特定的指導原則製作帶有函數的圖數據類型。初始化一個結構變量爲NULL,但調用時它不爲null
我必須有一個函數來初始化一個空圖。在這個函數中,我將第一個頂點設置爲NULL。只是測試這個,我運行我的num_vertices方法,我得到了分段錯誤。它應該返回0.
在我自己的調試之後,我已經知道在某個新圖上調用init函數之後,調用num_vertices函數會以某種方式傳遞一個非NULL的頂點,即使init函數集它爲NULL。因此,我的num_vertices方法正在運行通過爲我的圖分配的所有內存,直到遇到seg故障。
爲什麼會發生這種情況,我如何將它設置爲NULL,以便我的num_vertices有效?
我的圖結構(需要做類似這樣的):
typedef struct Edge Edge;
typedef struct Vertex Vertex;
typedef struct Graph Graph;
struct Graph {
Vertex *vertex;
};
struct Vertex {
/* use a tree to store vertices */
Vertex *left;
Vertex *right;
char *name;
Edge *edge; /* the edge between this vertex and its root */
};
struct Edge {
unsigned int cost;
};
我init_graph(),併爲num_vertices():
void init_graph(Graph *graph) {
graph = (Graph *)malloc(sizeof(Graph));
graph->vertex = NULL;
}
int num_vertices(Graph graph) {
return count_vertices(graph.vertex);
}
int count_vertices(Vertex *vertex) {
int count = 0;
if (vertex != NULL) {
count += count_vertices(vertex->left);
count++;
count += count_vertices(vertex->right);
}
return count;
}
最後,代碼我使用測試這一點,得到了賽格故障:
int main() {
Graph graph;
init_graph(&graph); /* initialize new graph */
assert(num_vertices(graph) == 0); /* seg fault here */
printf("It all worked!\n");
return 0;
}
你爲什麼先*分配內存到'graph-> vertex'然後**然後**用'NULL'覆蓋那個設置指針?! –
'(Graph ** graph)和* graph = malloc(...)'或者返回一個Graph * –
這些片段如何編譯? 'int num_vertices(Graph graph)'應該是'int num_vertices(struct Graph graph)'。請發佈顯示問題的[Minimal,Complete和Verifiable示例](http://stackoverflow.com/help/mcve)。 –