void init(int *a) {
int *b = malloc(sizeof(int));
*b = 4;
a = b;
printf("b address %d\n", b);
printf("a address %d\n", a);
printf("%d\n",*a);
}
int main()
{
int *a = malloc(sizeof(int));
printf("a address %d\n", a);
init(a);
printf("a address %d", a);
return 0;
}
will print the output
a address 32206864
b address 32211008
a address 32211008
4
a address 32206864
Here, the init function is initializing the value for a
. However, this is done is incorrect and I am trying to determine why. Observe that once the init function ends the pointer a
forgets the address it's supposed to point to. I assume this has something to do with the fact that a
is set to b
, a pointer that gets popped off the stack once the function ends.
But why does this make sense? Shouldn't a
remember what memory address it's been set to? After all, the scope of a
is the main function, not the init function.