#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.
It does work; it just doesn't do what you think it does.
In foo()
, a = b
changes the pointer a
to point to whatever b
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 by b
, you need to use *a = *b
, similar to how you do the assignments in the function already.
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 in main()
, 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:
void foo(int **a, int **b) {
**a = 5;
**b = 6;
*a = *b;
}
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:
int main(void) {
int a, b;
int * ptrA = &a;
int * ptrB = &b;
foo(&ptrA, &ptrB);
printf("%d, %d (%d, %d)", *ptrA, *ptrB, a, b);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With