In one sense, any variable in C is just a convenient label for a chunk
of the computer's memory that contains the variable's data. A
pointer, then, is a special kind of variable that contains the
location or address of that chunk of memory. (Pointers are so
called because they point to a chunk of memory.) The address
contained by a pointer is a lengthy number that enables you to pinpoint
exactly where in the computer's memory the variable resides.
Pointers are one of the more versatile features of C. There are many
good reasons to use them. Knowing a variable's address in memory
enables you to pass the variable to a function by reference
(See Variable parameters.) 1
Also, since functions are just chunks of code in the computer's memory,
and each of them has its own address, you can create pointers to
functions too, and knowing a function's address in memory enables you to
pass functions as parameters too, giving your functions the ability to
switch among calling numerous functions. (See Function pointers.)
Pointers are important when using text strings. In C, a text string is
always accessed with a pointer to a character -- the first character of
the text string. For example, the following code will print the text
string Boy howdy!:
Pointers are important for more advanced types of data as well. For
example, there is a data structure called a "linked list" that uses
pointers to "glue" the items in the list together. (See Data structures, for information on linked lists.)
Another use for pointers stems from functions like the C input routine
scanf. This function accepts information from the keyboard, just
as printf sends output to the console. However, scanf
uses pointers to variables, not variables themselves. For example, the
following code reads an integer from the keyboard:
This, by the way, is how the
phrase ``pass by reference'' entered the jargon. Like other pointers, a
variable parameter ``makes a reference'' to the address of a variable.