Lets suppose you assign a value of NULL
to a before you call function f1
. Now the way f1 is defined it takes its argument(pointer to an int
) by value. That is b
will be another variable of type int *
which will be a copy of a
. So b
too will have a value of NULL
. Now in f1
you change the value by b
by assigning it the address of memory allocated dynamically using malloc
. Lets say that memory address is 0x123
. As a result of this assignment, b
has changed its value from NULL
to 0x123
but a
(in main
) continues to hold NULL
, because changing b will not change a
, as they are two separate variables. As a result of this when you return from function f1
a will remain unchanged.
There are 2 ways to solve this. One you can make the function f1
return the value of the changed b
and then assign it back to a in main
and two, you can pass the a by address so that any changes made in f1
will affect a in main
too.
// f1 now returns the value of b.
int* f1() {
int *b = malloc(sizeof(int));
*b = 5;
return b;
}
int main() {
int *a = NULL;
a = f1(); // assign the return value of f1 to a.
printf("%d\n", *a); // prints 5...not its *a not just a.
return 0;
}
.
// f1 now takes the address of a.
void f1(int **b) {
*b = malloc(sizeof(int)); // you are actually altering a indirectly.
**b = 5;
}
int main() {
int *a = NULL;
f1(&a); // now pass the address of a to f1.
printf("%d\n", *a); // prints 5...not its *a not just a.
return 0;
}