How to pass matrix as parameter in C?

Asked

Viewed 698 times

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)

1 answer

0

The following are the changes made to the code: inclusion of stdlib library. h, inclusion of job signatures before main, inclusion of variables l and c of type int containing the value of rows and columns and a inclusion of variable **integer type matrix being a pointer

#include <stdio.h>
#include <stdlib.h>
#define linhas 3
#define colunas 3

void ImprimeMatriz(int **matriz, int l, int c);
void LiberaMatriz(int **matriz, int l);

int main()
{
   int **matriz;
   int i,j;
   int l = linhas;
   int c = colunas;

   //Alocando linhas da matriz com malloc

  matriz = (int**)malloc(linhas*sizeof(int*));

  //Alocando colunas da matriz com malloc
  for(i=0;i<colunas;i++){
     matriz[i] = (int*)malloc(colunas*sizeof(int));
  }

 //Inserindo valores na matriz;
 for(i=0;i<linhas;i++){
    for(j=0;j<colunas;j++){
        matriz[i][j] = i+j;
    }
 }

 ImprimeMatriz(matriz, l, c);
 LiberaMatriz(matriz,linhas);

  return 0;
}

//Imprimindo matriz
 void ImprimeMatriz(int **matriz, int l, int c){
   int i,j;
   for(i=0;i<l;i++){
     for(j=0;j<c;j++){
        printf("\t%d",matriz[i][j]);
     }
     printf("\n");
   }
 }


//Como foi alocado um espaço na memória é preciso libera-lo
void LiberaMatriz(int **matriz, int l){
  int i;
  for(i=0;i<l;i++){
    //Liberamos primeiro as linhas
    free(matriz[i]);
  }
  free(matriz);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.