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);
}
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
– Filipe
@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".
– user105951
@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.
– Isac