【发布时间】:2016-05-27 20:58:59
【问题描述】:
我正在编写一个代码来实现图形的邻接矩阵。但是我遇到了运行时错误。谁能指出我错在哪里?
代码:
#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 时,它一直工作到 graph->Adj = malloc(sizeof(graph->V * graph->V));,但在 graph->Adj[0][0] = 9; 时出现错误。为什么???
【问题讨论】:
-
错误是什么?
-
更新了错误。
标签: data-structures graph dynamic-arrays adjacency-matrix