Programming in C

(Barry) #1

274 Chapter 11 Pointers


pointer to the specified function. An ampersand is permitted in front of the function
name, but it’s not required.
If the lookupfunction has not been previously defined in the program, it is necessary
to declare the function before the preceding assignment can be made. So, a statement
such as
int lookup (void);
is needed before a pointer to this function can be assigned to the variable fnPtr.
You can call the function that is indirectly referenced through a pointer variable by
applying the function call operator to the pointer, listing any arguments to the function
inside the parentheses. For example,
entry = fnPtr ();
calls the function pointed to by fnPtr, storing the returned value inside the variable
entry.
One common application for pointers to functions is in passing them as arguments to
other functions.The standard C library uses this, for example, in the function qsort,
which performs a “quicksort” on an array of data elements.This function takes as one of
its arguments a pointer to a function that is called whenever qsortneeds to compare
two elements in the array being sorted. In this manner,qsortcan be used to sort arrays
of any type, as the actual comparison of any two elements in the array is made by a user-
supplied function, and not by the qsortfunction itself. Appendix B, “The Standard C
Library,” goes into more detail about qsortand contains an actual example of its use.
Another common application for function pointers is to create what is known as dis-
patchtables.You can’t store functions themselves inside the elements of an array.
However, it is valid to store function pointersinside an array. Given this, you can create
tables that contain pointers to functions to be called. For example, you might create a
table for processing different commands that will be entered by a user. Each entry in the
table could contain both the command name and a pointer to a function to call to
process that particular command. Now, whenever the user enters a command, you can
look up the command inside the table and invoke the corresponding function to
handle it.

Pointers and Memory Addresses


Before ending this discussion of pointers in C, you should note the details of how they
are actually implemented. A computer’s memory can be conceptualized as a sequential
collection of storage cells. Each cell of the computer’s memory has a number, called an
address, associated with it.Typically, the first address of a computer’s memory is numbered


  1. On most computer systems, a “cell” is called a byte.
    The computer uses memory for storing the instructions of your computer program,
    and also for storing the values of the variables that are associated with a program. So, if
    you declare a variable called countto be of type int, the system assigns location(s) in

Free download pdf