Page 1
POINTERS
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 alsobe 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 voi d ) replaces c h a r * as the proper type for a
generic pointer.
Pointers and Addresses
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 c h a r, a pair of one-byte
cells can be treated as a s h o r t integer, and four adjacent bytes form a i ong. A pointer is a group
of cells (often two or four) that can hold an address. So if c is a c h a r and p is a pointer that
points to it, we could represent the situation this way:
p = &c;
assigns the address of c to the variable p, and p is said to ''point to'' c . The & operator only
applies to objects in memory: variables and array elements. It cannot be applied to expressions,
constants, or r e g i s t e r variables.
The unary operator * is the indirection or dereferencing operator; when applied to a pointer, it
accesses the object the pointer points to. Suppose that x and y are integers and i p is a pointer to
i n t . This artificial sequence shows how to declare a pointer and how to use & and *:
Page 2
POINTERS
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 alsobe 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 voi d ) replaces c h a r * as the proper type for a
generic pointer.
Pointers and Addresses
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 c h a r, a pair of one-byte
cells can be treated as a s h o r t integer, and four adjacent bytes form a i ong. A pointer is a group
of cells (often two or four) that can hold an address. So if c is a c h a r and p is a pointer that
points to it, we could represent the situation this way:
p = &c;
assigns the address of c to the variable p, and p is said to ''point to'' c . The & operator only
applies to objects in memory: variables and array elements. It cannot be applied to expressions,
constants, or r e g i s t e r variables.
The unary operator * is the indirection or dereferencing operator; when applied to a pointer, it
accesses the object the pointer points to. Suppose that x and y are integers and i p is a pointer to
i n t . This artificial sequence shows how to declare a pointer and how to use & and *:
int x = 1, y = 2, z[10];
int *ip;
ip = &x;
y = *ip;
*ip = 0;
ip = &z[0];
The declaration of x, y, and z are what we've seen all along. The declaration of the pointer i p .
i n t * ip ;
is intended as a mnemonic; it says that the expression *i p is an i n t . The syntax of the declaration
for a variable mimics the syntax of expressions in which the variable might appear. This
reasoning applies to function declarations as well. For example,
d o u b le *dp, a t o f ( c h a r * );
says that in an expression *dpand a t o f (s ) have values of d o u b le, and that the argument of
a t o f is a pointer to c h a r.
You should also note the implication that a pointer is constrained to point to a particular kind of
object: every pointer points to a specific data type. If i p points to the integer x, then *i p can occur
in any context where x could, so
* ip = * ip + 10;
increments *ip by 10.
The unary operators * and & bind more tightly than arithmetic operators, so the assignment
y = * ip + 1
takes whatever i p points at, adds 1, and assigns the result to y, while
* ip += 1
increments what i p points to, as do
++*ip and (* ip )+ +
The parentheses are necessary in this last example; without them, the expression would increment
ip instead of what it points to, because unary operators like * and ++ associate right to left.
Finally, since pointers are variables, they can be used without dereferencing. For example, if iq is
another pointer to i n t ,
Page 3
POINTERS
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 alsobe 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 voi d ) replaces c h a r * as the proper type for a
generic pointer.
Pointers and Addresses
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 c h a r, a pair of one-byte
cells can be treated as a s h o r t integer, and four adjacent bytes form a i ong. A pointer is a group
of cells (often two or four) that can hold an address. So if c is a c h a r and p is a pointer that
points to it, we could represent the situation this way:
p = &c;
assigns the address of c to the variable p, and p is said to ''point to'' c . The & operator only
applies to objects in memory: variables and array elements. It cannot be applied to expressions,
constants, or r e g i s t e r variables.
The unary operator * is the indirection or dereferencing operator; when applied to a pointer, it
accesses the object the pointer points to. Suppose that x and y are integers and i p is a pointer to
i n t . This artificial sequence shows how to declare a pointer and how to use & and *:
int x = 1, y = 2, z[10];
int *ip;
ip = &x;
y = *ip;
*ip = 0;
ip = &z[0];
The declaration of x, y, and z are what we've seen all along. The declaration of the pointer i p .
i n t * ip ;
is intended as a mnemonic; it says that the expression *i p is an i n t . The syntax of the declaration
for a variable mimics the syntax of expressions in which the variable might appear. This
reasoning applies to function declarations as well. For example,
d o u b le *dp, a t o f ( c h a r * );
says that in an expression *dpand a t o f (s ) have values of d o u b le, and that the argument of
a t o f is a pointer to c h a r.
You should also note the implication that a pointer is constrained to point to a particular kind of
object: every pointer points to a specific data type. If i p points to the integer x, then *i p can occur
in any context where x could, so
* ip = * ip + 10;
increments *ip by 10.
The unary operators * and & bind more tightly than arithmetic operators, so the assignment
y = * ip + 1
takes whatever i p points at, adds 1, and assigns the result to y, while
* ip += 1
increments what i p points to, as do
++*ip and (* ip )+ +
The parentheses are necessary in this last example; without them, the expression would increment
ip instead of what it points to, because unary operators like * and ++ associate right to left.
Finally, since pointers are variables, they can be used without dereferencing. For example, if iq is
another pointer to i n t ,
iq = ip
copies the contents o f i p into i q , thus m aking i q point to w hatever i p pointed to.
Pointers and Function Arguments
Since C passes argum ents to functions by value, there is no direct w ay for the called function to
alter a variable in the calling function. For instance, a sorting routine m ight exchange tw o out-
oforder argum ents w ith a function called swap. It is not enough to w rite
sw ap (a, b ) ;
w here the swap function is defined as
v o id s w a p (in t x, i n t y)
{
i n t tem p;
temp = x;
x = y;
y = tem p;
}
B ecause o f call by value, swap can't affect the argum ents a and b in the routine that called it.
The function above swaps copies o f a and b . The w ay to obtain the desired effect is for the
calling program to pass pointers to the values to be changed:
swap(&a, &b);
Since the operator & produces the address o f a variable, & a is a pointer to a. In swap itself, the
param eters are declared as pointers, and the operands are accessed indirectly through them.
v o id s w a p (in t *px, i n t *py) /* in te r c h a n g e *px and *py * /
{
i n t tem p;
temp = *px;
*px = *py;
*py = tem p;
}
Pointer argum ents enable a function to access and change objects in the function that called it. As
an exam ple, consider a function g e t i n t that perform s free-form at input conversion by breaking a
stream o f characters into integer values, one integer per call. g e t i n t has to return the value it
found and also signal end o f file w hen there is no m ore input. These values have to be passed
Page 4
POINTERS
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 alsobe 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 voi d ) replaces c h a r * as the proper type for a
generic pointer.
Pointers and Addresses
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 c h a r, a pair of one-byte
cells can be treated as a s h o r t integer, and four adjacent bytes form a i ong. A pointer is a group
of cells (often two or four) that can hold an address. So if c is a c h a r and p is a pointer that
points to it, we could represent the situation this way:
p = &c;
assigns the address of c to the variable p, and p is said to ''point to'' c . The & operator only
applies to objects in memory: variables and array elements. It cannot be applied to expressions,
constants, or r e g i s t e r variables.
The unary operator * is the indirection or dereferencing operator; when applied to a pointer, it
accesses the object the pointer points to. Suppose that x and y are integers and i p is a pointer to
i n t . This artificial sequence shows how to declare a pointer and how to use & and *:
int x = 1, y = 2, z[10];
int *ip;
ip = &x;
y = *ip;
*ip = 0;
ip = &z[0];
The declaration of x, y, and z are what we've seen all along. The declaration of the pointer i p .
i n t * ip ;
is intended as a mnemonic; it says that the expression *i p is an i n t . The syntax of the declaration
for a variable mimics the syntax of expressions in which the variable might appear. This
reasoning applies to function declarations as well. For example,
d o u b le *dp, a t o f ( c h a r * );
says that in an expression *dpand a t o f (s ) have values of d o u b le, and that the argument of
a t o f is a pointer to c h a r.
You should also note the implication that a pointer is constrained to point to a particular kind of
object: every pointer points to a specific data type. If i p points to the integer x, then *i p can occur
in any context where x could, so
* ip = * ip + 10;
increments *ip by 10.
The unary operators * and & bind more tightly than arithmetic operators, so the assignment
y = * ip + 1
takes whatever i p points at, adds 1, and assigns the result to y, while
* ip += 1
increments what i p points to, as do
++*ip and (* ip )+ +
The parentheses are necessary in this last example; without them, the expression would increment
ip instead of what it points to, because unary operators like * and ++ associate right to left.
Finally, since pointers are variables, they can be used without dereferencing. For example, if iq is
another pointer to i n t ,
iq = ip
copies the contents o f i p into i q , thus m aking i q point to w hatever i p pointed to.
Pointers and Function Arguments
Since C passes argum ents to functions by value, there is no direct w ay for the called function to
alter a variable in the calling function. For instance, a sorting routine m ight exchange tw o out-
oforder argum ents w ith a function called swap. It is not enough to w rite
sw ap (a, b ) ;
w here the swap function is defined as
v o id s w a p (in t x, i n t y)
{
i n t tem p;
temp = x;
x = y;
y = tem p;
}
B ecause o f call by value, swap can't affect the argum ents a and b in the routine that called it.
The function above swaps copies o f a and b . The w ay to obtain the desired effect is for the
calling program to pass pointers to the values to be changed:
swap(&a, &b);
Since the operator & produces the address o f a variable, & a is a pointer to a. In swap itself, the
param eters are declared as pointers, and the operands are accessed indirectly through them.
v o id s w a p (in t *px, i n t *py) /* in te r c h a n g e *px and *py * /
{
i n t tem p;
temp = *px;
*px = *py;
*py = tem p;
}
Pointer argum ents enable a function to access and change objects in the function that called it. As
an exam ple, consider a function g e t i n t that perform s free-form at input conversion by breaking a
stream o f characters into integer values, one integer per call. g e t i n t has to return the value it
found and also signal end o f file w hen there is no m ore input. These values have to be passed
back by separate paths, for no m atter w hat value is used for EOF, that could also be the value o f an
input integer.
One solution is to have g e t i n t return the end o f file status as its function value, w hile using a
pointer argum ent to store the converted integer back in the calling function. This is the schem e
used by s c a n f as well
The follow ing loop fills an array w ith integers by calls to g e t i n t :
i n t n, a rra y [S IZ E ], g e t i n t ( i n t * );
f o r (n = 0; n < SIZE & & g e tin t(& a rra y [n ]) != EOF; n++)
;
Each call sets a r r a y [n ] to the next integer found in the input and increm ents n . N otice that it is
essential to pass the address o f a r r a y [n ] to g e t i n t . O therw ise there is no w ay for g e t i n t to
com m unicate the converted integer back to the caller.
O ur version o f g e t i n t returns EOF for end o f file, zero if the next input is not a num ber, and a
positive value if the input contains a valid number.
# in c lu d e < c ty p e .h >
i n t g e tc h ( v o id ) ;
v o id u n g e t c h ( i n t ) ;
i n t g e t i n t ( i n t *pn)
{
i n t c, s ig n ;
w h ile ( is s p a c e ( c = getc h ()));
i f (!is d ig it(c ) & & c != EOF & & c != '+' & & c != '- ')
{
ungetch(c); r e t u r n 0;
}
s ig n = (c == '- ' ) ? -1 : 1;
i f (c == '+' || c == '- ')
c = getch();
for (*pn = 0; i s d i g i t ( c ) , c = getch())
*pn = 10 * *pn + (c - '0 ') ;
*pn *= s ig n ;
i f (c != EOF)
ungetch(c);
r e t u r n c;
}
Throughout g e t i n t , *pnis used as an ordinary i n t variable. W e have also used g e tc h and
u n g e tc h so the one extra character that m ust be read can be pushed back onto the input.
Read More