I know why this works:
#include <stdio.h>
void cool_number(int **number) {
int value = 42;
int *p = &value;
*number = p;
}
int main () {
int *number;
cool_number(&number);
printf("number is %d\n", *number);
return 0;
}
What I don't understand is why this doesn't (in my machine it prints 3700
or something like that).
#include <stdio.h>
void cool_number(int **number) {
int value = 42;
int *p = &value;
int **x = &p;
number = x;
}
int main () {
int *number;
cool_number(&number);
printf("number is %d\n", *number);
return 0;
}
Why aren't both equivalent?
I assume they're not equivalent because
number
is passed by value, on the stack, as is standard for function parameters. Any changes that you make directly tonumber
inside ofcool_number()
are modifying the local copy on the stack, and are not reflected in the value ofnumber
inmain()
.You get around this in the first example by dereferencing
number
, which tells the computer to modify some specific location in memory that you also happen to have a pointer to back inmain()
. You don't have this in the second example, so all that happens is that you make the localnumber
pointer point to somewhere else, without actually updating any memory location being referred to back inmain()
. Thus nothing you do shows up once you get back tomain()
.And since
value
is local to thecool_number()
function, setting a reference to it that will be accessed aftercool_number()
returns isn't guaranteed to work and certainly shouldn't be used in any code outside of a trivial/toy example. But in this specific instance it's not really related to why you're seeing different results between the two pieces of code.