【问题标题】:adjacency matrix don't alloc properly邻接矩阵没有正确分配
【发布时间】:2020-05-05 20:19:29
【问题描述】:

我有一个图形结构,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】:
   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));
}

【讨论】:

    【解决方案2】:

    您为紧凑的 2D 矩阵分配空间,但 adjmatrix 的类型意味着间接 2D 矩阵,即:指向 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      • 2017-05-04
      • 1970-01-01
      • 2017-12-05
      • 2018-08-17
      • 1970-01-01
      • 2022-11-15
      相关资源
      最近更新 更多