Error reading values for a dynamically allocated matrix

Asked

Viewed 80 times

1

Good afternoon,

I’m doing some coding to study more about C memory allocation with the malloc function, and I was developing a code to allocate an array and then read values and save it, but it’s giving error during execution and closing the program, someone could help me and explain why the mistake.

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);
}

1 answer

1


The problem is the return of the function alocar:

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
}

Where the type does not play with what has been declared. The function declares that it returns a int** but the very matriz is the type int** which causes the address of matriz be the type int ***. Notice you used &matriz or matrix address.

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

...|10|Warning: Return from incompatible Pointer type [enabled by default] ...

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

To solve just change the return for:

return matriz;
  • Thank you, it really makes sense, I had seen an example I used & so I used but it was a different thing but thanks helped

  • @Isac else wouldn’t be the fact that he didn’t dislocate the mémoria? So...not that it’s a mistake, but rather a "not good programming practice".

  • 1

    @DC-10 It is indeed a relevant point what you mentioned, and which I often warn, but as in this case right after memory is used the program ends, it does not make a difference. But in a different scenario using the same function can quickly become a memory leak.

Browser other questions tagged

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