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.
- JRahmAdmin
Nice work, Rodrigo! It's been since 1996 since I've dealt directly with C on a consistent basis, so it was nice to revisit an old friend. It also led me to investigate why python (my personal fave) doesn't really have pointers, and this article on Real Python does a great job showing the differences between C and python architecture, why pointers aren't really necessary in python, and of course ways to simulate or engage with pointers if you really must.
Yeah, C is the old school thing that never gets outdated. I liked the last bit about emulating pointers in Python. Thanks for sharing that, Jason!