Error reading values for a dynamically allocated array

1

Good afternoon,

I'm doing some code to study more about memory allocation in C with the malloc function, and I was developing a code to allocate an array and then read values and save it, but it is giving error while executing and closing the program , someone could help me and explain why the error.

Code Snippet:

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

int ** alocar(){
     int ** matriz;
     int i;
     matriz = (int **) malloc(3 * sizeof(int *));
     for(i = 0; i < 3; i++)
        matriz[i] = (int *) malloc(3 * sizeof(int));
     return (&matriz);
}

void lerValores(int ** matriz){
     int i, j;
     for(i = 0; i < 3; i++){
         for(j = 0; j < 3; j++){
             printf("Valor[%d][%d]:", i, j);
             scanf("%d", &matriz[i][j]);
             printf("\n");
         }
     }
}

void main()
{
    int ** matriz;
    matriz = alocar();
    lerValores(matriz);
}
    
asked by anonymous 11.12.2017 / 20:33

1 answer

1

The problem is with the return of the alocar function:

int ** alocar(){
     int ** matriz;
     int i;
     matriz = (int **) malloc(3 * sizeof(int *));
     for(i = 0; i < 3; i++)
        matriz[i] = (int *) malloc(3 * sizeof(int));
     return (&matriz); //<-- aqui
}

In which type does not play with what was declared. The function declares that it returns a int** but the matriz itself is of type int** which causes the matriz address to be of type int *** . Note that you used &matriz or array address.

We should always pay close attention to the warnings that the compiler gives, as these are almost always errors. In your case the warning you give when compiling the code is as follows:

  

... | 10 | warning: return from incompatible pointer type [enabled by   default] ...

That is precisely the reason for the error, that the returned type and the declared type are incompatible.

To resolve, just change return to:

return matriz;
    
11.12.2017 / 21:00