A pointer stores a memory address.
But I hear you say: can't an int or long also do that? All you need is the number of the memory address.
Well, the magical thing about a pointer is that it can use a special operator!
What? (I hear you say)
Yes!
Here is what it does: it allows you to obtain the value that is stored at that memory address.
What does a pointer store again? (a memory address)
But it can also obtain a value at that memory address.
You can't do that with an int, I've tried [0].
We call this operator the dereference operator [1].
It looks like a star
*
That's the one. That's the dereference operator.
One of the confusing things is that when you declare a pointer, you also use a *
Example
int *a;
//or
int * a;
//or
int* a;
In those 3 examples, the * is not a dereference operator. It simply indicates that it is a pointer. In this case we have an int pointer.I always like to view it as: we have an int! And this is how many times we're allowed to use the dereference operator: one time
How many times are you allowed to use it on this pointer?
int *****super_pointer
That's right, five times!So when you have
int val = 10;
int *a = val;
Then what is the value of a? It's 10. What do pointers store? Addresses. So what address is this? Address 10!But when it comes to memory addresses in computers, there is a tricky part to it. In normal operating systems, low addresses are reserved for special things, I think it's the kernel in this case. So if you dereference that particular address, the OS/runtime environment won't allow you to. They will give you an error called a segmentation fault.
So you need to get a valid address of the variable val, but how do you do that? We have another operator for that, which I like to call the address-of operator.
So when you have
int val = 10;
int *a = &val; // & is the address-of operator
Then the variable a has the valid memory address we want!
There's much more to learn, but I'll leave it at this for now.
---
I recommend people who start learning pointers/programming to use GDB with the TUI graphical interface. One could also print the values, but it's easier to see what really happens. For that there are two steps you need to do:
- Watch a GDB with TUI tutorial: https://www.youtube.com/watch?v=AxsSXMPD3N4
- And then also display all the cpu registers. The reason for that: your variable values will be visible in there (in hexadecimal).
All the GDB commands: https://sourceware.org/gdb/onlinedocs/gdb/TUI-Commands.html (look for the regs option)
[0] https://stackoverflow.com/questions/35379191/cannot-cast-var...
[1] Side note: I used to have trouble with the word dereferencing. If you have to, here is why it's called that way: https://stackoverflow.com/questions/35372786/what-does-the-d...