这是用malloc()定义矩阵的方法
我从GeeksForGeeks 那里得到了一些版本。
具有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]);
}
}
我们可以将这些代码放入graph_create(int nodes)函数中。
代码
struct graph {
int** adj; /**< Adjacency matrix. */
int n; /**< Number of nodes in graph. */
}G;
struct graph *graph_create(int nodes) {
struct graph * tmp = &G;
int r = nodes, c = nodes, i, j, count;
//arr[r][c]
G.adj = (int **)malloc(r * sizeof(int *));
for (i=0; i<r; i++){
*(G.adj + i) = (int *)malloc(c * sizeof(int));
//arr[i] = (int *)malloc(c * sizeof(int));
}
count = 0;
for (i = 0; i < r; i++)//3
for (j = 0; j < c; j++)//4
G.adj[i][j] = ++count; // OR *(*(arr+i)+j) = ++count
for (i = 0; i < r; i++){
printf("\n");
for (j = 0; j < c; j++){
printf("%d ", G.adj[i][j]);
}
}
return tmp;
}
int main()
{
struct graph * d = graph_create(5);
printf("\n");
return 0;
}
我们知道图的邻接矩阵有 n*n 维。
为此,我们使用节点作为行和列。
编辑
为了安全地使用malloc() 函数,我们必须通过使用这些块调用free() 来释放malloc() 保留的内存位置。 (类似于Mobius的回答)
就在main() 中的return 0; 语句之前调用这个:
free ((*d).adj);
所需的头文件:
#include <stdio.h>
#include <stdlib.h> // for** malloc()**, **free()**