void main(){
Info* info;
inserir(info);
//O erro acontece na linha de baixo, como se o
//que foi feito na função inserir não persistiu de fato
//na estrutura
printf("%d\n", info->val);
}
What happens here is that the info variable does not change value before and after the function inserir()
.
The initial value of the variable (garbage because it was not initialized) is the value that will be used in the printf.
As you suggest in your answer, you can solve by assigning a value before calling the function; or instead of passing the value you pass the address.
int main(void) {
Info *info;
inserir(&info);
printf("%d\n", info->val);
free(info);
}
void inserir(Info **x) {
*x = malloc(sizeof **x); // falta validacao
(*x)->val = 10;
}
Still another solution is to use the function return value
int main(void) {
Info *info;
info = criarinfo();
printf("%d\n", info->val);
free(info);
}
Info *criarinfo(void) {
Info *x;
x = malloc(sizeof *x); // falta validacao
x->val = 10;
return x;
}
In my opinion your solution is the best!
Note that in the two solutions above the malloc
and the free
are in different places. It becomes much easier to manage the memory when the function that makes the malloc
'and responsible for also doing the free
.
The correct 'and use
int main()
. The use ofvoid main()
unnecessarily limits your program to implementations that accept this form.– pmg