int** matriz = initMatriz(rows, cols);
From this point on, how do I find the number of rows and number of columns?
Well, the answer is right there. Just look at the parameters rows
and cols
and they will give you the answer.
Okay, you might want to know how to do this if you no longer have access to rows
and cols
values. And the answer is that you can not do that, at least not in a portable way. The pointer value is a number that says in which memory address the memory block that is allocated starts, but nothing says about its size.
If you know the deep details of your malloc
ployment implementation, you may be able to find this information in memory allocation tables that are created or some other type of internal information held by malloc
. However, a solution based on this is inherently non-portable.
The solution adopted in almost all cases includes you encapsulating the pointer to the array and the size of the array allotted together in the same structure for this. In this way, you eliminate the fundamental problem that is not having the size of the allocated area along with that area itself. For example:
typedef struct {
int rows;
int cols;
int** pointer;
} Matriz;
Matriz* initMatriz(int rows, int cols) {
int i, j;
// Aloca a memória para todas as linhas.
int **matriz = (int**) malloc(rows * sizeof(int*));
for (i = 0; i < rows; i++) {
// Para cada linha, eu aloco o número de colunas.
matriz[i] = (int*) malloc(cols * sizeof(int));
// Inicializa.
for (j = 0; j < cols; j++) {
matriz[i][j] = 0;
}
}
Matriz *resultado = (Matriz *) malloc(sizeof(Matriz));
resultado->rows = rows;
resultado->cols = cols;
resultado->pointer = matriz;
return resultado;
}
To destroy an array in order to free memory:
void freeMatriz(Matriz *matriz) {
for (int i = 0; i < matriz->rows; i++) {
free(matriz->pointer[i]);
}
free(matriz->pointer);
free(matriz);
}