Вот способ определить матрицу с 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()
мы должны освободить ячейки памяти, зарезервированные malloc()
, вызвав free()
с этими блоками. (аналогично ответу Mobius)
непосредственно перед оператором return 0;
в main()
вызовите это:
free ((*d).adj);
Требуемые заголовочные файлы:
#include <stdio.h>
#include <stdlib.h> // for** malloc()**, **free()**
person
EsmaeelE
schedule
01.10.2017
int **adj
всего лишь указатель на целое число указателя, которое указывает на первые элементы вашей матрицы. Сначала используйтеmalloc()
, чтобы выделить для этого память. - person EsmaeelE   schedule 01.10.2017struct graph
- person EsmaeelE   schedule 01.10.2017