C中具有邻接矩阵的图

C中具有邻接矩阵的图,c,graph-algorithm,adjacency-matrix,C,Graph Algorithm,Adjacency Matrix,我有一个struct: struct graph { int** adj; /**< Adjacency matrix. */ int n; /**< Number of nodes in graph. */ }; 如何使用双指针创建矩阵 以下是使用malloc()定义矩阵的方法 我从一些版本中了解到 2D整数矩阵与int**和malloc() int r = 3, c = 4, i, j, count; //arr[r][c] int **arr = (int

我有一个
struct

struct graph {
    int** adj; /**< Adjacency matrix. */
    int n; /**< Number of nodes in graph. */
};

如何使用双指针创建矩阵

以下是使用
malloc()定义矩阵的方法
我从一些版本中了解到

2D整数矩阵与
int**
malloc()

int r = 3, c = 4, i, j, count;

//arr[r][c]
int **arr = (int **)malloc(r * sizeof(int *));

for (i=0; i<r; i++){
    *(arr +i) = (int *)malloc(c * sizeof(int));
    //arr[i] = (int *)malloc(c * sizeof(int));
}

// Note that arr[i][j] is same as *(*(arr+i)+j)
count = 0;
for (i = 0; i <  r; i++)//3
    for (j = 0; j < c; j++)//4
        arr[i][j] = ++count;  // OR *(*(arr+i)+j) = ++count

for (i = 0; i <  r; i++){
    printf("\n");
    for (j = 0; j < c; j++){
        printf("%d ", arr[i][j]);
    }
}
我们知道图的邻接矩阵有n*n维。 为此,我们使用节点作为行和列

编辑

为了安全地使用
malloc()
函数,我们必须通过使用这些块调用
free()
来释放
malloc()
保留的内存位置。(与答案相似)

就在
返回0之前main()
中的code>语句调用此函数:

自由的((*d.adj)

所需的头文件:

#include <stdio.h>
#include <stdlib.h> // for** malloc()**, **free()**
#包括
#包含//用于**malloc()**,**free()**

为了分配矩阵,您需要为实际矩阵数据分配空间(大小
宽度*高度*大小(int)

在使用
int**
矩阵的设置中,您还需要分配一个指针数组,该数组将指向每行的开头,如果要避免这种情况,您可以通过执行类似
size\u t offset=row*width+column
的操作来计算偏移量

要分配指针,我们需要
height*sizeof(int*)
bytes

最后,需要在数组中分配行指针

总之,代码应该如下所示:

int ** allocate_matrix(size_t width, size_t height){
    int *  values = malloc(height * width * sizeof(int));
    int ** rows   = malloc(height * sizeof(int*));

    size_t i;
    for (i = 0; i < height; i++) {
        size_t offset = i * width;
        rows[i] = &values[offset];
    }

    return rows;
}

// the returned matrix can me indexed like `matrix[row][column]`

请向我们展示您迄今为止所做的尝试。Graph struct first element是
int**adj
只是指向指向矩阵第一个元素的指针整数的指针。首先使用
malloc()
为其分配内存。您的函数获取图形中的节点数,以邻接矩阵的形式实现该图形,然后将其作为
struct graph
返回,如果在create函数中我定义struct graph graph,malloc是graph->adj=(int*)malloc(sizeof(int*)*n)?这两个答案中有一个回答了你的问题吗?您应该选择一个作为正确的解决方案,或者问一个问题。@pipox这是否回答了您的问题?
#include <stdio.h>
#include <stdlib.h> // for** malloc()**, **free()**
int ** allocate_matrix(size_t width, size_t height){
    int *  values = malloc(height * width * sizeof(int));
    int ** rows   = malloc(height * sizeof(int*));

    size_t i;
    for (i = 0; i < height; i++) {
        size_t offset = i * width;
        rows[i] = &values[offset];
    }

    return rows;
}

// the returned matrix can me indexed like `matrix[row][column]`
void free_matrix(int ** rows) {
    // this points to the beginning of our region of memory for values;
    int * values = rows[0]; 

    free(values);
    free(rows);
}