1
Hello.
In general, I know that to pass an array as a parameter of a function in C, we have to specify the size of its dimensions. But this makes the function less generic.
I was thinking of using the pointer-to-pointer idea to get around this, but I don’t think I understood very well how it would be possible.
I tried the code below. Please tell me what is wrong.
#include <stdio.h>
#define N_LINHAS 3
#define N_COLUNAS 3
void imprime_matriz(int **matriz, int linhas, int colunas){
int i,j;
for(i=0;i<linhas;i++){
for(j=0;j<colunas;j++){
printf("%d\t",matriz[i][j]);
}
printf("\n");
}
}
int main()
{
int i,j,matriz[N_LINHAS][N_COLUNAS];
for(i=0;i<N_LINHAS;i++){
for(j=0;j<N_COLUNAS;j++){
matriz[i][j] = i*j;
}
}
imprime_matriz(matriz,N_LINHAS,N_COLUNAS);
return 0;
}
In this case, this matrix is a simple pointer, not a pointer pointer. Then, you pass as
*matriz
. However, to access your fields, you need to access the matrix without the "syntax sugar" of the function variable: you need to calculate the "linear index" of the matrix item (matriz[i*colunas + j]
if I’m not mistaken)– Jefferson Quesado