Programming in C

(Barry) #1

262 Chapter 11 Pointers


sets pxto point nelements farther in the array,no matter what type of element is contained in
the array.
The increment and decrement operators ++and --are particularly handy when deal-
ing with pointers. Applying the increment operator to a pointer has the same effect as
adding one to the pointer, while applying the decrement operator has the same effect as
subtracting one from the pointer. So, if textPtris defined as a charpointer and is set
pointing to the beginning of an array of chars called text, the statement
++textPtr;
sets textPtrpointing to the next character in text, which is text[1]. In a similar fash-
ion, the statement
--textPtr;
sets textPtrpointing to the previous character in text, assuming, of course, that
textPtrwas not pointing to the beginning of textprior to the execution of this state-
ment.
It is perfectly valid to compare two pointer variables in C.This is particularly useful
when comparing two pointers in the same array. For example, you can test the pointer
valuesPtrto see if it points past the end of an array containing 100 elements by com-
paring it to a pointer to the last element in the array. So, the expression
valuesPtr > &values[99]
is TRUE (nonzero) if valuesPtris pointing past the last element in the valuesarray,
and is FALSE (zero) otherwise. Recall from previous discussions that you can replace the
preceding expression with its equivalent
valuesPtr > values + 99
because valuesused without a subscript is a pointer to the beginning of the values
array. (Remember, it’s the same as writing &values[0].)
Program 11.11 illustrates pointers to arrays.The arraySumfunction calculates the sum
of the elements contained in an array of integers.

Program 11.11 Working with Pointers to Arrays
// Function to sum the elements of an integer array

#include <stdio.h>

int arraySum (int array[], const int n)
{
int sum = 0, *ptr;
int * const arrayEnd = array + n;

for ( ptr = array; ptr < arrayEnd; ++ptr )
sum += *ptr;
Free download pdf