我正在使用Adjacency Matrix制作图表.
这是我的头文件 - graph.h -
typedef struct Node{
int vertex;
}Node_t;
typedef Node_t *Row;
typedef struct graph_t{
int noOfVertices;
Row *rowPointer;
}graph_t, *graph_p;
Run Code Online (Sandbox Code Playgroud)
这是我的定义文件 - graph.c -
graph_p createGraph(int noOfVertices){
int i,
j;
graph_p graph = (graph_p)malloc(sizeof(graph_t));
graph->noOfVertices = noOfVertices;
graph->rowPointer = (Row *)malloc(noOfVertices * sizeof(Row));
fprintf(stdout, "\nValue of graph->rowPointer: %p\n", graph->rowPointer);
for(i = 0; i < noOfVertices; i++){
Row r = (Node_t *)malloc(noOfVertices * sizeof(Node_t));
fprintf(stdout, "Value of r: %p\n", r);
graph->rowPointer[i] = &r;
fprintf(stdout, "Value of graph->rowPointer[%d]: %p\n", i, graph->rowPointer[i]);
}
for(i = 0; i < noOfVertices; i++){
for(j = 0; j < noOfVertices; j++){
Row* row = graph->rowPointer[i];
fprintf(stdout, "Value of row: %p\n", row);
row[j]->vertex = 0;
fprintf(stdout, "Value of row[%d]->vertex: %d\n", j, row[j]->vertex);
}
}
return graph;
}
Run Code Online (Sandbox Code Playgroud)
不过我的输出是 -
graph-> rowPointer的
值:003E3C50 r的值:003E3C70 graph-> rowPointer [0]的
值:0028FEDC r的
值:003E3C90 graph- > rowPointer [1]的
值:0028FEDC r的
值:003E3CB0 graph- > rowPointer [2]:0028FEDC
r的值:003E3CD0 graph-
> rowPointer [3]的
值:0028FEDC r的
值:003E3CF0 graph- > rowPointer [4]的
值:0028FEDC
行的值:0028FEDC 行的值[0] - > vertex:0
行的值:0028FEDC行的
值[1] - >顶点:0
行的
值:0028FEDC 行的值[2] - >顶点:0
行的值:0028FEDC
然后,代码进入无限循环.
因此,当我分配时似乎有问题graph->rowPointer[i] = &r;,为什么会这样?我认为我已经正确分配了指针.谁能告诉我有什么问题?
谢谢!
你是这么认为的
graph->rowPointer[i] = &r;
Run Code Online (Sandbox Code Playgroud)
是有问题的.您正在接收(并保留)自动变量的地址.退出块时,变量超出范围,留下悬空指针.
在我看来,你有一个太多级别的指针rowPointer.一个就够了.