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

2

In the exec I am developing, I try to pass a dynamically created array created with the malloc function, but doing so compiles the pointer type as incompatible.

#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;
}
    
asked by anonymous 28.02.2018 / 21:25

1 answer

2

In C, in the function argument, you need to tell the compiler how many columns you have in your array, due to the fact that the array is nothing more than a vector, but with a rows and columns logic, for 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 row it has a grouping of X memory locations (columns) with values, so it requires you to declare at least the number of columns. To solve your problem, you can declare a quantity 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.

    
28.02.2018 / 22:37