#include <stdio.h>
void functionx(int *ptr) {
*ptr = *ptr + 100;
}
int main(void) {
int i = 100;
int *p = &i;
printf("i = %d\n", i);
functionx(p);
printf("i = %d\n", i);
return 0;
}
How does the pointer change the value of i variable? Why is i=200?
You have your variable i
in memory:
+---+ | i | +---+
Then you create a pointer p
and make it point to i
:
+---+ +---+ | p | --> | i | +---+ +---+
Now you call your function, creating a copy of the pointer p
and store it in the variable ptr
. That means you have two pointers both pointing to the same variable i
:
+---------------+ | p (from main) | ---------\ +---------------+ | +---+ >--> | i | +----------------------+ | +---+ | ptr (from functionx) | --/ +----------------------+
If you're wondering about how dereferencing with the *
operator works, lets get back to the simpler case with only p
and i
:
+---+ +---+ | p | --> | i | +---+ +---+
By dereferencing the pointer variable p
we follow the arrow and end up with the variable i
.
So *p
and i
are both the same.
In the main
function you could to the same as functionx
by using p
instead:
*p = 300;
printf("i = %d\n", i); // Will print that i is equal to 300