#include <stdio.h>
#include <stdlib.h>
void foo(int *a, int *b);
void foo(int *a, int *b) {
*a = 5;
*b = 6;
a = b;
}
int main(void) {
int a, b;
foo(&a, &b);
printf("%d, %d", a, b);
return 0;
}
Why a = b (foo) doesn't work? printf outputs "5, 6" Thank you.
The call to
foo()
ends with its local variables pointing to the same addres, the one of stored in b. This change is not reflected inmain()
, the caller.I you liked to actually do this and make this change pemanent, then you would have to pass a pointer to a pointer to
foo()
(so you can change them), instead of their simple values:I have just observed that your code is incompatible with that modification, anyway, since you cannot change two normal variables to point to each other. You'd have to also modify
main()
this way:Using a pseudo-memory map,
In
main()
,In the function
foo()
,So, when in
foo()
's scope,So the final map in
foo()
's scope is:It does work; it just doesn't do what you think it does.
In
foo()
,a = b
changes the pointera
to point to whateverb
points to. It has no effect on anything outside of the function; it only changes the pointers.If you want to change the value of the int pointed to by
a
to be the same as the value of the int pointed to byb
, you need to use*a = *b
, similar to how you do the assignments in the function already.I'm not sure what you're going after... if it's to get
a
andb
to contain the same value, try*a = *b
.Because when
foo
is called, the values of the pointers are copied into the function. If you want to change the values of the pointers themselves, you need to pass a pointer to a pointer into the function.In
foo
,a
andb
are separate local variables. Setting them to have the same value has no effect on the previous values - the last line offoo
currently does nothing, basically.Within
foo
,a
is initially a pointer to the same location asa
inmain
, andb
is a pointer to the same location asb
in main. The last line just makes the value ofa
infoo
the same asb
- namely a pointer to the same location asb
in main. So if you add a lineat the end of
foo
, then you'd see output of "5, 7".(Your code would definitely be easier to talk about if you used different variable names in
main
andfoo
, by the way.)If you're trying to make
a
andb
withinmain
"aliased" to each other, you're not going to be successful. They're separate local variables on the stack, and will remain so. You can't make the stack "shrink" to alias the two, whatever you do.