The C Programming Language, Ansi C
5.1 Pointers and Addresses
Chapter 5 - Pointers and Arrays
A pointer is a variable that contains the address of a variable. Pointers are
much used in C, partly because they are sometimes the only way to express a
computation, and partly because they usually lead to more compact and efficient
code than can be obtained in other ways. Pointers and arrays are closely
related; this chapter also explores this relationship and shows how to exploit
it.
Pointers have been lumped with the goto statement as a marvelous way to create impossible-to-understand programs. This is certainly true when they are used carelessly, and it is easy to create pointers that point somewhere unexpected. With discipline, however, pointers can also be used to achieve clarity and simplicity. This is the aspect that we will try to illustrate.
The main change in ANSI C is to make explicit the rules about how pointers can be manipulated, in effect mandating what good programmers already practice and good compilers already enforce. In addition, the type void * (pointer to void) replaces char * as the proper type for a generic pointer.
Let us begin with a simplified picture of how memory is organized. A typical
machine has an array of consecutively numbered or addressed memory cells that
may be manipulated individually or in contiguous groups. One common situation
is that any byte can be a
char
, a pair of one-byte cells can be treated
as a
short
integer, and four adjacent bytes form a
long
. A pointer
is a group of cells (often two or four) that can hold an address. So if
c
is a
char
and
p
is a pointer that points to it, we could represent
the situation this way:
_[image omitted]_
The unary operator & gives the address of an object, so the statement
p = &c;
assigns the address of
c
to the variable
p
, and
p
is said to point to''
c
. The
&