Hands-on C: Understanding Pointers step by step
Quick Intro
Pointers have always been the most confusing aspect of C for new learners.
As a former lecturer, I find simple hands-on examples are the best to get one started.
In this article, I will explain the following:
- What a pointer is
- How a pointer is declared in C
- How to assign a memory address to a pointer
- How to change values using pointers
- How to move pointer to a different memory address
What is a pointer?
It's literally a variable that stores and point to the memory address of another variable.
Don't worry, it should be clear once we go through some examples.
How a pointer is declared in C
How to assign a memory address to a pointer
Now, imagine there's a variable x like this:
The &x just means we're assigning to p the memory address of x:
In order to retrieve the value 5 from p, we also need to use *p because p (without *) retrieves the memory address of x and *p goes after the value stored in the memory's address.
Here's the proof:
Notice that C understands that adding & in front of variable retrieves its memory address.
How to retrieve pointer's value
Retrieving pointer's is also known as dereferencing pointer.
If we change *p we also change x.
We can also assign the value that *p points to a different variable too (effectively changing the value of x):
How to change values using pointers
When we point a pointer to an array, it will point to the memory address of array's first item at index 0:
The pointer behaves in the same way as if were making the changes to the array:
How to move pointer to a different memory address
In this example, I pointed p to A's memory address and then pointed p to n's memory address and that's fine:
Let's uncomment last line so we can see that we can't do the same with arrays, i.e. re-assigning values:
Hope that clarifies a bit of the mystery behind pointers.