Using Arrays with Functions

We have read the students' scores into an array, and now we want to write a function to compute something useful about the data, say the maximum score. To do this, we will need to pass the array to the function as an argument. Here is the prototype for a max() function:

int max(int data[], int dataLen); Note that in this case it is not necessary to provide the length of the array parameter (int data[]) since we are providing the number of elements in the parameter dataLen. When passing an array in this fashion, the function knows where in memory the array starts, but not it's length; the dataLen parameter is necessary to indicate the length.

Within the max() function, we can access the array data[] using square brackets as we would any other array. Computing the maximum value is simple:

int max(int data[], int dataLen) { int currentMax = data[0]; for (int i = 1; i < dataLen; i++) { if (data[i] > currentMax) { currentMax = data[i]; } } return currentMax; } The following code demonstrates how to call the max() function: const int NUM_STUDENTS = 100; int scores[NUM_STUDENTS] = { 0 }; int numScores = 0; // Code to read scores... int maxVal = max(scores, numScores); // compute max score When passing an array as an argument, we only provide the name of the array (scores in this example). The compiler knows that scores is really an array since it was declared that way in the function prototype. Technically, what is really being passed to the function is the address in memory of the first element of the scores[] array.

Note: the implementation of the maximum function given above assumes there is at least one item in the data[] array. How would you modify the function to handle the case in which data[] is empty?

There is an important difference between array parameters and primitive parameters: a function can modify the values in an array whereas it cannot modify the value of an argument of primitive type (primitive types are the basic types proided by C++, e.g. int, char, float, etc.). For example, the following function, curve(), adds five to each element of the data[] array:

void curve(int data[], int dataLen) { while (dataLen-- > 0) data[dataLen] += 5; } If we call this function with our scores[] array as the argument, each score will be increased by five points, and this change will be visible in the calling function. However, the changes to dataLen will not be visible to the calling function since it is a parameter of type int, which is a primitive type.