For some reason pointers are very scary. I remember when first learning about pointers, the teacher warned us about all kinds of pointer misuse, crashes, segmentation faults etc… I was so scared I couldn’t fall asleep
After growing up I realized there’s nothing to fear but the fear itself (and the god of segfaults).
Even many experienced programmers make mistakes with pointers.
So what are pointers? like you can guess from the name, pointers point to something.
This something can be data or function.
We’ll start with the simplest example:
pa = &a;
In the first line we defined an integer variable, basically what it means is we tell the computer to create a space in the memory for an integer number.
Another way to look at it, is we tell the computer to create a post-office box with enough space for an integer.
This post-office box must have an address. In order to get the address we use the “&” operator on the name.
In order to save the address, we need to create a post-office box with enough space to save addresses of integers. We use
int *variable_name to create a variable that can contain addresses of integers.
On the 3rd line we simply save the address of “a” in the variable “pa”.
Please notice an important point, “pa” is a variable, which means it also has an address, and to find the address of it we can use the “&” operator.
Ok now what? so we have an address of a variable, why do we need it? what can we do with it?
pa = &a;
*pa = 2;
Noticed the new line at the end? What we did was use the “*” operator on “pa” in order to fetch the variable that “pa” points at. Then we put inside the variable the value “2”. If we print “a” now we’ll see “2” as a result.
Another way to look at it (which I don’t totally recommend) is that “*” cancels “&”, for example “*&a” = “a”.
So… we can use the address of a variable to use that variable, still why can’t we just use the variable itself?
Well… if we wrote applications using just the main() function and if we didn’t have dynamic memory allocation, we wouldn’t need any pointers and life would be good.
After 398 words we’ve managed to cover the really really basics of pointers.
In order to understand pointers more deeply you need to learn about: dynamic memory allocation, heap, stack and pointers to functions.
These topics sounds complex but in reality they’re not that hard.
I’ll cover those topics in future posts.