Passing Pointers as Arguments to Functions
As you've probably seen up to this point, C functions receive arguments passed by value. What does this mean? When an variable is passed as an argument to a function, the variable itself is not actually given to the function. Instead, that variable's value (in other words, a copy of that variable) is passed into the function. For example:
So when this program runs, we see: x is 1 x is 0 x is 1
As mentioned earlier in this tutorial, a pointer is just like any other variable, with the exception that you can use pointer operators on the variable, like * and ). When you pass a pointer to a function, just like any variable, you are actually passing a copy of the pointer's value, so any changes made to that pointer inside a function will not be visible outside of the function, for example:
As above, this displays something like: x is 0x1bc9723f x is 0x0 x is 0x1bc9723f Notice that, just as above, the value of the pointer x is the same before and after the call to set_to_null(), even though the function set_to_null() modified its copy of x. The function only modifies a copy of main's x and therefore main is unaffected by the changes. /PARARAPH
How Pointers Allow Us To Sidestep ThisIf pointers behave just like any other variable, why bring it up here in the "how can pointers be useful" section? Because pointers allow us to sidestep this little predicament. Let's return to the idea of the function set_to_zero() in which we'd like to set a variable to 0. As we saw, we can't pass in the variable itself because then we'd just be passing a copy, and any changes made to that copy would go away as soon as the function returned. But what if we passed a pointer to that variable into the function? The function can then dereference the copy of the pointer (which, as it is a copy, will point to exactly the same memory as the original) and access the original variable that exists in the calling function. Passing arguments like this is known as passing by reference; instead of passing a copy of the variable into the function, we're passing in a reference to that variable (the pointer), allowing it to be accessed inside the called function.
Back to our original example, this time passing by reference:
When Will I Use This?
All the time. After a certain point, virtually every program you write will use pointers for this purpose. If you've used scanf(), you've already passed variables by reference). Practice and understand pointers and you will be rewarded.