Home > Software engineering >  How to use a matrix as an argument for a function in c?
How to use a matrix as an argument for a function in c?

Time:12-09

I'm trying to use the C code below to generate a matrix based on a given formula, but not being able to pass the array as an argument to the function that generates it, because the compiler output errors that say something about incompatible types. But why? I've created an int array, so why it says that an array of int passed as an int value is wrong? How can I correctly pass the matrix as an argument to the function?

Here is the code that i have implemented:

#include <stdio.h>
#include <stdlib.h>

int imprimeMatriz (int*, int, int);
int main(){
    int m,n;
    printf("Entre com linhas e colunas da matriz");
    scanf("%d %d",&m,&n);
    int  matrix[m][n];
    imprimeMatriz(matrix,m,n);
     for (int i=0 ; i<n ; i  ){
        for (int j=0; j<n;j  ){
    printf("%d",&matrix[i][j]);
        }
    }
    return 0;
}

int imprimeMatriz(int p, int m, int n){

    for (int i=0 ; i<n ; i  ){
        for (int j=0; j<n;j  ){
    p = (5-i)*(j 1);
    }
        }

   return p;
}

And those are the errors that I get when trying to compile with cc -o matrix matrix.c

matrix.c: In function ‘main’:
matrix.c:10:19: warning: passing argument 1 of ‘imprimeMatriz’ from incompatible pointer type [-Wincompatible-pointer-types]
   10 |     imprimeMatriz(matrix,m,n);
      |                   ^~~~~~
      |                   |
      |                   int (*)[n]
matrix.c:4:20: note: expected ‘int *’ but argument is of type ‘int (*)[n]’
    4 | int imprimeMatriz (int*, int, int);
      |                    ^~~~
matrix.c: At top level:
matrix.c:19:5: error: conflicting types for ‘imprimeMatriz’; have ‘int(int,  int,  int)’
   19 | int imprimeMatriz(int p, int m, int n){
      |     ^~~~~~~~~~~~~
matrix.c:4:5: note: previous declaration of ‘imprimeMatriz’ with type ‘int(int *, int,  int)’
    4 | int imprimeMatriz (int*, int, int);
      |     ^~~~~~~~~~~~~

Also have tried solutions proposed here and here, but without success

CodePudding user response:

IMO the best way is to use pointers to array.

Example:

void initMatrix(size_t rows, size_t cols, int (*matrix)[cols])
{
    for(size_t row = 0; row < rows; row  )
        for(size_t col; col < cols; col  )
            matrix[row][col] = rand();
}

CodePudding user response:

Thing is that you cant pass arrays like that in a function. but you can pass every single elements from your matrix into your function like in exemple1 or if you really want to pass the entire array, you can pass it as a pointer. It's a little bit more complicated but it's in exemple 2.

Exemple1 Exemple2

  • Related