Pointers

A pointer in C is a special type of variable which holds the address of a location in memory. We already mentioned pointers briefly when we introduced arrays. We noted that an array name is actually a pointer. It points to the memory location of the first element of the array. But an array name is a special kind of pointer and in particular is not defined the same way as an ordinary pointer.

The following two lines of code show how to define a pointer. There is a variable of type int, called num1, which is storing the value 3, then there is a pointer to that variable, called pnum, which stores the address of the variable num1.

    int num1 = 3;
    int * pnum = &num1;

The critical feature of this declaration is the int * which says that pnum is a pointer (that's what the * represents) to a variable of type int. We say pnum points to num1.

You might be sitting there thinking, "but &num1 already gives me the address of the variable num1, so why am I defining another variable (in this case pnum) to put this address in?" Well, of course the same argument also works for the variable num1. The number 3 is already an integer, so why do I define a variable (called num1) to put that in? Why don't I just use the number 3 every time I need it? The answer to this question is the same as the answer to the pointer variable question. Why do we ever define any kind of variable? Because we may want to change the value later. Or, worse still, we may not actually know what the value is to be, since it may come from the user, or depend on something they enterered, and we can have no idea of what the user is going to enter whilst we are still writing the program that they are going to use later on!

So a pointer is just a variable which contains the address of some other variable or memory location.