Another use is to allow a function to modify values from the calling function.
Is there another way to do this without pointers? The answer is probably plain and clear in front of my face but right now I feel like I can't see the forest for the trees. If you know what I mean.
The only other way to modifiy a value inside a function is to make the value global (declared outside all functions). Using global variables we can make the code very simple in small programs, but in larger programs it actaully can make things more confusing.
int x; /* declare x as global, outside of all functions */
...
x = 10;
printf("%d\n", x);
do_something(); /* call function with address of x */
printf("%d\n", x);
...
void do_something(void)
{
x = x + 10;
}
Globals aren't bad, but use them in moderation and only when needed. Be careful to make the global varaible name something unique so it won't cause unexpected problems in other functions.
If x is not global the code looks like this:
...
int x;
x = 10;
printf("%d\n", x);
do_something(x); /* call function with a copy of x */
printf("%d\n", x);
...
void do_something(int x)
{
x = x + 10;
}
This will
not modify x in the calling function. The reason is that x is passed
by value to the do_something() function. This means that a new copy of x is made and modified inside the function. Once the function is complete, this new copy is destroyed and the original copy is used again.
We can use pointers to modify the original x value like this:
...
int x;
x = 10;
printf("%d\n", x);
do_something(&x); /* call function with address of x */
printf("%d\n", x);
...
void do_something(int *x)
{
*x = *x + 10;
}
This time the a new variable is still created, but instead of holding a copy of the
value of x, it holds a copy if the
address of x. This is called "pass by reference". The do_something() function was changed to modify the value pointed to by x. This time, the value of x in the calling function should've been changed.