邻接矩阵不能正常分配

问题描述 投票:0回答:1

我有一个图结构,其中有 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;
}
c graph malloc adjacency-matrix
1个回答
0
投票
   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));
}

0
投票

你为一个紧凑的二维矩阵分配了空间 但这个矩阵的类型是什么? adjmatrix 意味着一个间接的二维矩阵,即:一个指向数组的 V 的数组指针。V 整数。

你可以用一个循环和 calloc() 所以它已经被初始化为 0:

struct Graph *createGraph(int V) {
    struct Graph *graph = malloc(sizeof(*graph));
    graph->V = V;
    graph->adjmatrix = calloc(V, sizeof(*graph->adjmatrix));
    for (int i = 0; i < V; i++) {
        graph->adjmatrix[i] = calloc(V, sizeof(*graph->adjmatrix[i]));
    }
    return graph;
}
© www.soinside.com 2019 - 2024. All rights reserved.