c-马洛克破坏了功能



我的malloc破坏了我的程序。把它取下来会起作用,但我需要它。有人能解释一下我做错了什么吗。提前感谢!!

我的图中有这个函数。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;

这个在我的图表中。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;

我怀疑这个问题是因为你希望这个函数为你分配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 开始

最新更新