我正在为graph.But编写实现邻接矩阵的代码,我正在获得运行时error.Can,有人建议我哪里错了吗?
代码:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct Graph{
int V;
int E;
int **Adj;
};
void test(struct Graph *graph)
{
graph->E = 5;
graph->V = 4;
graph->Adj = malloc(sizeof(graph->V * graph->V));
graph->Adj[0][0] = 9;
graph->Adj[0][1] = 7;
graph->Adj[0][2] = 2;
graph->Adj[0][3] = 5;
printf("Hello %d\n",graph->Adj[0][2]);
}
int main()
{
struct Graph *graph = malloc(sizeof(struct Graph));
test(graph);
}如果我在主要功能上做同样的工作,我不明白我写测试函数和做测试函数时做错了什么?
在主要功能中完成的代码:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct Graph{
int V;
int E;
int **Adj;
};
int main()
{
struct Graph *graph = malloc(sizeof(struct Graph));
graph->E = 5;
graph->V = 4;
graph->Adj = malloc(sizeof(graph->V * graph->V));
graph->Adj[0][0] = 9;
graph->Adj[0][1] = 7;
graph->Adj[0][2] = 2;
graph->Adj[0][3] = 5;
printf("Hello %d\n",graph->Adj[0][2]);
}为test function进行运行时test function调试它可以工作到graph->Adj = malloc(sizeof(graph->V * graph->V));,但是在graph->Adj[0][0] = 9;,它会给出error.Why?
发布于 2016-05-27 21:03:58
你做错了。您正在使用指向指针的指针。因此,您必须首先使用malloc来获得动态分配的数组指针。然后,您必须为每一行分配它。
试试这个:
graph->Adj = (int **)malloc(graph->v * sizeof(int *));
for (i=0; i<graph->v; i++)
graph->Adj[i] = (int *)malloc(graph->v * sizeof(int));https://stackoverflow.com/questions/37492162
复制相似问题