Previous: 6.4 Common Errors
Up: 6 Pointers
Next: 6.6 Exercises
Previous Page: 6.4 Common Errors
Next Page: 6.6 Exercises
In this Chapter we have introduced a new data type, a pointer. We have seen how we can declare variables of this type using the * and indicating the type of object this variable can point to, for example:
int * iptr;
float * fptr;
char * cptr;
declare three pointer variables, iptr which can point to an integer
cell, fptr which can point to a cell holding a floating point
variable, and cptr which can point to a character cell.
We have seen how we can assign values to pointer variables using the ``address of'' operator, & as well as from other pointer variables. For example,
{ int x;
int * ip;
int * iptr;
iptr = &x;
ip = iptr;
. . .
}
declares an integer variable, x, and two integer pointers,
ip and iptr,
which can point to integers (we can read this last declaration from
right to left, as saying
that `` iptr points to an int'').
We then assign the address of x to the pointer variable, iptr,
and the pointer in iptr to the variable, ip.
We have also shown how pointer variables may be used to indirectly access the value in a cell using the dereference operator, *:
y = *iptr;which assigns the value of the cell pointed to by iptr to the variable, y. Values may also be stored indirectly using pointer variables:
*iptr = y;which assigns the value in the variable, y, to the cell pointed to by iptr.
We have also seen that we can pass pointers to functions and use them to modify the values of cells in the calling function. For example:
main()
{ int x, y, z;
z = set_em( &x, &y};
. . .
}
int set_em( int *a, int *b)
{
*a = 1;
*b = 2;
return 3;
}
Here the function, set_em will set the values 1, 2, and 3 into
the variables x, y, and z respectively. The first
two values are assigned indirectly using the pointers passed to the
function, and the third is returned as the value of the function and
assigned to z by the assignment statement in main().
This, the function, set_em(), has ``effectively'' returned
three values.
Finally, we have used this new indirect access mechanism to write several programs, including an update to our payroll program. As we will see in succeeding chapters, pointers are very useful in developing complex programs. The concept of pointers may be confusing at first, however, a useful tool for understanding the behavior of a program using pointers is to draw the memory picture showing which to cells each pointer is pointing.