7.7 Arrays and Functions
Arrays can be passed to function as arguments. When specifying an array parameter, you indicate the array with empty square brackets as shown in the function prototype below:
- int sum(int values[], int size);
You will note that the capacity of the array (the number of physical elements in the array) is not included. This is due to the fact that arrays are passed by reference the same way lists are passed to functions in Python. Thus, an array of any size can be passed to a function so long as it stores the given type of data. While a function can be designed to work with an array of a specific size, typically they are designed with subarray processing in mind. That is, the number of elements currently used in the array is also passed to the function.
Calling the Function
When calling a function that requires an array, only the name of the array is provided as the argument to to the function. For example, consider the grades array from the previous section
We can call the sum function and pass it the grades array:
- int sum;
- sum = sum(grades, numGrades);
Implementing the Function
The implementation of a function that includes an array argument is no different than using the array within the same function in which it was created. Consider the the implementation of the sum function:
- int sum(int values[], int size)
- {
- total = 0;
- for(int i = 0; i < size; i++)
- total = total + values[i];
- return total;
- }

Note that even if the size of the array were specified as part of the parameter,
- int sum(int values[12], int size)
it would be ignored by the compiler. Thus, it is considered good style to omit the size so as to not confuse the reader of the code.
As indicated earlier, arrays are passed to functions by reference. Thus, any changes made to the array in the function are made to the actual array and not a copy of the array. Suppose we want to increase each student's grade by a specific amount (i.e. give each student 5 additional points). We can design and implement a function addPoints:
- void addPoints(int values[], int size, int extraPoints)
- {
- for(int i = 0; i < size; i++)
- values[i] = values[i] + extraPoints;
- }
and call the function with our grades array above:
- addPoints(grades, numGrades, 5);
Since the array is passed by reference, the values of the elements in the original array will be increased by 5 points:
What happens if you call a function and lie about the size? For example, calling
- sum = sum(grades, 100);
even though grades has a size of 7 and a capacity of 12?
Design and implement a function that accepts a floating point array along with its size and clears the array by setting each element to 0.
- void clear(float list[], int size)
- {
- for(int i = 0; i < size; i++)
- list[i] = 0.0;
- }

