Pointers in C are variables that hold an address in the memory. That address is the location of another variable.
But why are pointers so difficult understand, yet so popular in C?
- Because they give great powers in your hands. Remember from the previous lesson on functions - usually when we call a function with parameters, that function works with copies of the arguments. So the function couldn't change the variables that we send as arguments. However, if the argument is a pointer to a variable, the function can work with and change the original variable.
Advertise on this site. I promise you will like the rates :)
The syntax to create and assign a pointer is as follows:
<type> * <name> = &<name of the pointed variable>
As you see, the pointer has a type. It must be the same as the type of the variable that it points to. Otherwise your compiler would warn you that you are trying to do initialization from incompatible pointer type. As a result the code might not compile or not behave as expected. That is because when you try to use the value hold in that address, it will try to interpret it as the type of the pointer (while it is not).
The asterisk says that this will be a pointer variable. The spaces around the asterisk are optional. You can write any of the following:
I prefer the second version, because that way it stays like a part of the type and is separated from the name.
The & symbol in front of the variable takes the address of the variable, instead of its actual value. This way, we assign the pointer to hold the address.
The term "dereference" means that we access the value behind the address, that it points to. Here is an easy example to start with:
Here we create a pointer to the float variable "temperature". Next we use that pointer to print the value. Then we again dereference the pointer, in order to change the value of the original variable. If you run the code, you will see that the value of the original variable is now changed to 37.5 degrees.
To better understand what really happens when we use the address operator and the dereference operator, look at the following example. I strongly recommend that you also run it and examine the result yourself:
Like I said above - we use pointers in order to give a function access to the original variable in the memory. This allows the function to change the original value.
Remember how we read numbers from the console? We used scanf() and it required that we pass the variable that we read with the address operator &. This is exactly the same - instead of passing a copy of our variable, we pass its address and scanf() accepts that in a pointer and then it could read into our variable.
In the next example we create and call the function swap(). It accepts two pointers to int and swaps their values:
There is much more to pointers like
However, these are more difficult topics that I will explain in the next C tutorial - advanced level.