How to send a dynamically created matrix as a parameter to a function?

Asked

Viewed 105 times

2

In the execution I am developing I try to pass a matrix created dynamically created with the function malloc, but in doing so the compiler points to type incompatible with pointer.

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

void substituiNegativos(int c, int mat[][c]){

    int i, j;

    for(i=0; i< 2; i++){
        for(j=0; j< 2; j++){

            if(mat[i][j] < 0){
                mat[i][j] = abs(mat[i][j]);
            }
        }
    }

    for(i=0; i< 2; i++){
        for(j=0; j<2; j++){

            printf("%d ", mat[i][j]);
        }
        printf("\n");
    }
}

int main()
{

    int i, j, l, c;

    printf("Numero de linhas: ");
    scanf("%d", &l);

    printf("Numero de colunas: ");
    scanf("%d", &c);

    int **mat = (int**)malloc(l * sizeof(int));

    for(i=0; i<l; i++){

        mat[i] = (int*)malloc(c * sizeof(int));

        for(j=0; j<c; j++){

            printf("Insira o numero: ");
            scanf("%d", &mat[i][j]);
        }
    }

    substituiNegativos(c, mat);

    return 0;
}

1 answer

2


In C, in the function argument, you need to tell the compiler how many columns you have in your matrix, due to the fact that the matrix is nothing more than a vector, but with a row and column logic, example:

int main()
{
    int matriz[3][3] = {10,20,30,40,50,60,70,80,90};
    int i, j;

    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
        {
            printf("%d ", matriz[i][j]);
        }
        printf("\n");
    }
}

the result will be this:

Matriz[i][j] -> 10 20 30 40 50 60 70 80 90
         [i] -> 0  0  0  1  1  1  2  2  2
         [j] -> 1  2  3  1  2  3  1  2  3

The compiler needs to know that for such a line he has a grouping of X memory positions (columns) with values, so it requires you to declare at least the number of columns. To solve your problem, you can declare a number of columns. Example:

void substituiNegativos(int c, int mat[][100])

Or declare a vector pointer. Example:

void substituiNegativos(int c, int *mat[])

Either one will work.

  • I appreciate the explanation, it worked, but I would also like to know more out of curiosity, if I could pass the argument this way void substituiNegativos(int c, int mat[][c]), being the variable c my column size, or C does not allow it. I thank you already.

  • Not allowed for two reasons: 1 - Its variable 'c' is local within the main function. It is only seen inside main. 2 - 'c' does not represent any value in the scope of the'void substituent(int c, int mat[][c])'. As I had explained, it is necessary to declare a value in the matrix column in a function scope

  • Thanks, it helped a lot.

Browser other questions tagged

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