首页 > 解决方案 > 邻接矩阵没有正确分配

问题描述

我有一个v表示节点数的图结构,**adjmatrix它是邻接矩阵,我在用 0 初始化所有元素时遇到问题,我在adjmatrix[0][0]=0.

结构如下所示:

struct Graph {
    int V;
    int **adjmatrix;
};

这是初始化图形的函数:

struct Graph *createGraph(int V) {
    struct Graph *graph = (struct Graph *)malloc(sizeof(struct Graph));
    graph->V = V;
    graph->adjmatrix = (int *)malloc(V * V * sizeof(int));
    int i, j;
    for (i = 0; i < V; ++i) {
        for (j = 0; j < V; j++) {
            graph->adjmatrix[i][j] = 0; //here is where i get segmentation fault
        }
    }
    return graph;
}

标签: cgraphmallocadjacency-matrix

解决方案


   graph->adjmatrix = (int **)malloc(V * sizeof(int*));
        graph->adjmatrix = (int *)malloc(V * V * sizeof(int));

是不正确的。
你需要做的是:

graph->adjmatrix=malloc(V*sizeof(int *));
for (int i=0;i<V;i++){
    graph->adjmatrix[i]=malloc(V*sizeof(int));
}

推荐阅读