A pointer is a variable that holds the memory address of another variable or function, which means that you can use a pointer to refer indirectly to a variable.
Why are pointers useful? The first, and most pragmatic, reason is that they have been part of the C family of languages right since the start and they’re very widely used, so you’ll need to know something about them. There are many other reasons though, and I’ve summarized a couple of the most important ones in this note.
First, pointers are one of the main ways that arguments are passed to functions. Arguments are usually passed by value—as a copy—so you can’t modify the value and expect it to get back to the calling code. Pointers let you pass arguments in such a way that you can modify them.
Second, some operations on series of data—such as values in arrays—can be performed very efficiently using pointers.
Although a pointer variable contains an address and therefore can store a memory address of any data type, pointer variables are declared to be data type specific. A pointer to an integral data type (int) can’t store the address of a double. The pointer variable is declared in the same way as the data type variable, but the pointer operator * (an asterisk) is appended to the data type:
int* pi; // pointer to an int double* pd; // pointer to a double char* pc; // pointer to a char
Every variable has an address, and that address can be obtained using the address of operator, which is an ampersand (&). The address of the variable can be stored in a pointer variable, and using that pointer, the contents of that variable can be manipulated by using the dereference operator * (an asterisk):
int x = 10, y = 0; int* pX = NULL; // Declare an integer pointer. pX = &x; // Store the address of the integer variable x. y = *pX; // Use the dereference operator to assign the // value of x to y. *pX = 20; // Use the dereference operator to assign 20 to x.
In the last two lines of the code, *pX can be read as “what pX points to.”
It might seem confusing that the asterisk is used for both the pointer operator and the dereference operator. You’ll find, however, that the pointer operator is only used when declaring variables, and the dereference operator is used in code. So it is obvious which operator an asterisk represents.