Pointers and Arrays 265
eliminate the variable ptrfrom the function and use arrayinstead, as shown in Program
11.12.
Program 11.12 Summing the Elements of an Array
// Function to sum the elements of an integer array Ver. 2
#include <stdio.h>
int arraySum (int array, const int n)
{
int sum = 0;
int const arrayEnd = array + n;
for ( ; array < arrayEnd; ++array )
sum += *array;
return sum;
}
int main (void)
{
int arraySum (int *array, const int n);
int values[10] = { 3, 7, -9, 3, 6, -1, 7, 9, 1, -5 };
printf ("The sum is %i\n", arraySum (values, 10));
return 0;
}
Program 11.12 Output
The sum is 21
The program is fairly self-explanatory.The first expression inside the forloop was omit-
ted because no value had to be initialized before the loop was started. One point worth
repeating is that when the arraySumfunction is called, a pointer to the valuesarray is
passed, where it is called arrayinside the function. Changes to the value of array(as
opposed to the values referenced by array) do not in any way affect the contents of the
valuesarray. So, the increment operator that is applied to arrayis just incrementing a
pointer to the array values, and not affecting its contents. (Of course, you know that
you canchange values in the array if you want to, simply by assigning values to the ele-
ments referenced by the pointer.)