图的邻接矩阵

Adjacency Matrix of Graph

我正在编写实现邻接矩阵的代码 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); 
}

如果我在 main 函数中做同样的事情 works.I 不明白我在编写测试函数并执行它时做错了什么?

在主函数中完成的代码:

#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 获取运行时 error.While 调试它一直有效到 graph->Adj = malloc(sizeof(graph->V * graph->V)); 但在 graph->Adj[0][0] = 9; 它给出 error.Why???

您使用了错误的 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));