我有一個問題,我的 malloc 破壞了我的程式。洗掉它會使它作業,但我需要它進一步。有人可以解釋一下我做錯了什么。提前致謝!!
我的graph.c中有這個功能
bool graph_initialise(graph_t *graph, unsigned vertex_count)
{
assert(graph != NULL);
graph = (struct graph_s*) malloc(sizeof(struct graph_s));
if (graph == NULL){return true;}
graph->vertex_count = vertex_count;
graph->adjacency_lists = (struct adjacency_list_s*) malloc(vertex_count * sizeof(struct adjacency_list_s));
if (graph->adjacency_lists == NULL){
return true;
}
int i;
for (i = 1; i < vertex_count; i){
graph->adjacency_lists[i].first = NULL;
}
return false;
這在我的 graph.h 中
typedef struct edge_s
{
/* Points to the next edge when this edge is part of a linked list. */
struct edge_s *next;
unsigned tail; /* The tail of this edge. */
unsigned head; /* The head of this edge. */
unsigned weight; /* The weight of this edge. */
} edge_t;
typedef struct adjacency_list_s
{
edge_t *first; /* Pointer to the first element of the adjacency list */
} adjacency_list_t;
/* Type representing a graph */
typedef struct graph_s
{
unsigned vertex_count; /* Number of vertices in this graph. */
unsigned edge_count; /* Number of edges in this graph. */
/* Pointer to the first element of an array of adjacency lists. The array
* is indexed by vertex number
*/
adjacency_list_t *adjacency_lists;
} graph_t;
uj5u.com熱心網友回復:
我懷疑這個問題是你期望這個函式為你分配 grph 然后在呼叫代碼中分配的圖形上操作(你沒有顯示呼叫代碼)
即你正在做類似的事情
graph *gptr;
graph_initialise(gptr,42);
printf("vc = %d", gptr->vertex_count);
問題是 grpah_initialize 沒有設定 gptr。你需要
bool graph_initialise(graph_t **gptr, unsigned vertex_count)
{
*gptr = (struct graph_s*) malloc(sizeof(struct graph_s));
graph_t *graph = *gptr;
if (graph == NULL){return true;}
graph->vertex_count = vertex_count;
graph->adjacency_lists = (struct adjacency_list_s*) malloc(vertex_count * sizeof(struct adjacency_list_s));
if (graph->adjacency_lists == NULL){
return true;
}
int i;
for (i = 1; i < vertex_count; i){
graph->adjacency_lists[i].first = NULL;
}
return false;
并像這樣稱呼它
graph *gptr;
graph_initialise(&gptr,42);
printf("vc = %d", gptr->vertex_count);
還有那個 for 回圈應該從 0 開始而不是 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/386847.html
上一篇:C記憶體泄漏以釋放鏈表
