【问题标题】:Adjacency Matrix of Graph图的邻接矩阵
【发布时间】: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-&gt;Adj = malloc(sizeof(graph-&gt;V * graph-&gt;V));,但在 graph-&gt;Adj[0][0] = 9; 时出现错误。为什么???

【问题讨论】:

  • 错误是什么?
  • 更新了错误。

标签: data-structures graph dynamic-arrays adjacency-matrix


【解决方案1】:

你做错了 malloc。您正在使用指向指针的指针。因此,您必须先 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));

【讨论】:

  • 谢谢你的回复。我知道那个方法但是我想知道为什么我的方法是错误的?
  • 更新了答案
  • 但是当我在主函数中做同样的事情时它会起作用。为什么在测试函数中有而不是在?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-24
  • 1970-01-01
  • 1970-01-01
  • 2016-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多