< Previous | Contents | Next >
Because an array name is a constant pointer, you can use it to efficiently pass an array to a function. That’s what I do next with the following line, which passes to increase() a constant pointer to the first element of the array and the number of elements in the array.
increase(highScores, NUM_SCORES);
Hin t
When you pass an array to a function, it’s usually a good idea to also pass the number of elements in the array so the function can use this to avoid attempting to access an element that doesn’t exist.
As you can see from the function header of increase(), the array name is accepted as a constant pointer.
void increase(int* const array, const int NUM_ELEMENTS)
The function body adds 500 to each score.
for (int i = 0; i < NUM_ELEMENTS; ++i)
{
array[i] += 500;
}
I treat array just like any array and use the subscripting operator to access each of its elements. Alternatively, I could have treated array as a pointer and substituted *(array + i) += 500 for the expression array[i] += 500, but I opted for the more readable version.
After increase() ends, control returns to main(). To prove that increase() did in fact increase the high scores, I call a function to show the scores.
display(highScores, NUM_SCORES);
The function display() also accepts highScore as a pointer. However, as you can see from the function’s header, the function accepts it as a constant pointer to a constant.
void display(const int* const array, const int NUM_ELEMENTS)
248 Chapter 7 n Pointers: Tic-Tac-Toe 2.0
By passing the array in this way, I keep it safe from changes. Because all I want to do is display each element, it’s the perfect way to go.
Finally, the body of display() runs and all of the scores are listed, showing that they’ve each increased by 500.
Hi n t
You can pass a C-style string to a function, just like any other array. In addition, you can pass a string literal to a function as a constant pointer to a constant.
Because an array name is a pointer, you can return an array using the array name, just as you would any other pointer to an object.