I found a function that frees matrix memory:
void free_matrix(int ***matrix, int rows, int cols) {
int row;
if (matrix != NULL && *matrix != NULL) {
for (row = 0; row < rows; row++) {
free((*matrix)[row]);
(*matrix)[row] = NULL;
}
free(*matrix);
*matrix = NULL;
}
}
I call the method as follows:
int **my_vector = create_matrix(5, 5);
free_matrix(&my_vector, 5, 5);
I don’t quite understand why the author decided to use ***matrix, and not **matrix, because in my other method, where I create the matrix, he does just that:
void fill_matrix(int **matrix, int rows, int cols) {
int row = 0;
int col = 0;
for (row = 0; row < rows; row++) {
for (col = 0; col < cols; col++) {
matrix[row][col] = ((row + 1) * 10) + col;
}
}
}
int **create_matrix(int rows, int cols) {
int row;
int **matrix = malloc(rows * sizeof(int *));
for (row = 0; row < rows; row++) {
matrix[row] = malloc(cols * sizeof(int));
}
return matrix;
}
There must be a reason why the author decided to use int ***matrixinstead int **matrix.
Goldi source
share