Programming in C

(Barry) #1

256 Chapter 11 Pointers


exchange (p1, p2);
printf ("i1 = %i, i2 = %i\n", i1, i2);

exchange (&i1, &i2);
printf ("i1 = %i, i2 = %i\n", i1, i2);

return 0;
}

Program 11.9 Output
i1 = -5, i2 = 66
i1 = 66, i2 = -5
i1 = -5, i2 = 66

The purpose of the exchangefunction is to interchange the two integer values pointed
to by its two arguments.The function header
void exchange (int * const pint1, int * const pint2)
says that the exchangefunction takes two integer pointers as arguments, and that the
pointers will not be changed by the function (the use of the keyword const).
The local integer variable tempis used to hold one of the integer values while the
exchange is made. Its value is set equal to the integer that is pointed to by pint1.The
integer pointed to by pint2is then copied into the integer pointed to by pint1, and the
val ue of tempis then stored in the integer pointed to by pint2, thus making the
exchange complete.
The mainroutine defines integers i1and i2with values of –5and 66 ,respectively.
Two integer pointers,p1and p2,are then defined and are set to point to i1and i2,
respectively.The program then displays the values of i1and i2and calls the exchange
function, passing the two pointers,p1and p2, as arguments.The exchangefunction
exchanges the value contained in the integer pointed to by p1with the value contained
in the integer pointed to by p2. Because p1points to i1,and p2to i2, the values of i1
and i2end up getting exchanged by the function.The output from the second printf
call verifies that the exchange worked properly.
The second call to exchangeis a bit more interesting.This time, the arguments that
are passed to the function are pointers to i1and i2that are manufactured right on the
spot by applying the address operator to these two variables. Because the expression &i1
produces a pointer to the integer variable i1, this is right in line with the type of argu-
ment that your function expects for the first argument (a pointer to an integer).The
same applies for the second argument as well. And as can be seen from the program’s
output, the exchangefunction did its job and switched the values of i1and i2back to
their original values.

Program 11.9 Continued
Free download pdf