As I said in “Understanding C pointers: Part 0,” I’m going to try to explain how C pointers work.
Let’s start with the basics. Here’s some simple C code:
int x = 23;
int y = x;
You can think of each variable as a box which holds the value of that variable. So in this example we have 2 boxes, named “x” and “y”. After these two statements execute the “x” box contains 23, and the “y” box also contains 23. The picture looks like this:
Pretty straightforward stuff. If we add this code:
x = 17;
the pictures changes to look like this:
Nothing too fancy there.
Next example: let’s add a pointer into the mix.
int x = 23;
int y = x;
int * p = & x;
If the * or & in the above code scare you, please take a deep breath and relax. We’ll get through this, I promise. 🙂
“x” is a variable of type integer. So is “y”. The “int *” before p means that p is a variable of type “pointer to integer” otherwise known as an “integer pointer.” Nothing magical there. The “&” before “x” can be read as the “address of x,” or “the box named x.” Which means the pointer “p” points to the box named “x”.
As in the previous examples we have a box named “x” and another box named “y”. This example adds a pointer to an integer called “p”. You can think of this pointer as simply another box, named “p”. The value in the “p” box is a pointer to another box. For the boxes “x” and “y” we can say things like “x holds the number 23,” but for the box “p” we say “p holds a pointer to the box named “x””.
A picture is worth at least a few words:
Watch what happens when we add this next line to the example:
*p = 17;
The * before the “p” tells us we’re changing the value of what “p” points to. We are not changing the value of “p” itself. The number 17 gets put wherever the value of the “p” box point to – which is the “x” box in this case. After this code runs our picture looks like this:
Notice that “p” has not changed. “p” still points to box “x”. Only the value in the box that “p” was pointing to changed.
Let’s add a couple more lines to that example:
p = & y;
*p = 42;
The first line changes the value in the box “p” to be a pointer to the box “y”. The 2nd line changes the value in the box that “p” points to be 42. The result looks like this:
Drawing these pictures may seem unnecessary, but I guarantee that drawing them will help you understand your code. Even if you understand pointers completely, when faced with a pointer-laden interview question it’s a good idea to draw your data structures and pointers. This way the interviewer can see how you’re thinking about the question, which is frequently more useful than simply getting the “right” answer.
Okay, that’s the basics. See – pointers aren’t that bad.
And it turns out that the way a computer actually implements variables/pointers is a lot like our simple “boxes” model. Tune in next time for more about that.