The real power of pointers comes into play when you start passing them to functions.
You could pass all kinds of parameters to functions and they’d be copied onto the stack, and then you could manipulate local copies of those variables from within the function, and then you could return a single value.
What if you wanted to bring back more than one single piece of data from the function?
What happens when you pass a pointer as a parameter to a function? Does a copy of the pointer get put on the stack? Yes it does. Remember EVERY SINGLE PARAMETER gets copied onto the stack and the function uses a copy of the parameter. Well, the same is true here. The function will get a copy of the pointer.
But, and this is the clever part: we will have set up the pointer in advance to point at a variable, and then the function can dereference its copy of the pointer to get back to the original variable! The function can’t see the variable itself, but it can certainly dereference a pointer to that variable! Example below:
#include <stdio.h>
void increment(int *p){ /* it accepts an int pointer */ *p = *p + 1; /* add one to p */}
int main(void){ int i = 10;
printf("i is %d\n", i); /* prints 10 */ increment(&i); /* note the address-of operator, turns it into a pointer */ printf("i is %d\n", i); /* prints 11 */
return 0;}The increment() function takes an int* as a parameter. We pass it an int* in the call by
changing the int variable i to an int* using the address-of operator. (Remember, a pointer is
an address, so we make pointers out of variables by running them through the address-of
operator.)
The increment() function gets a copy of the pointer on the stack. Both the original pointer
&i (in main()) and the copy of the pointer p (in increment()) point to the same address.
So dereferencing either will allow you to modify the original variable i! The function can
modify a variable in another scope!