C++ Passing Arrays to Functions

C++ Arrays

In C++, you can pass a pointer to an array by specifying the array name without an index.

In C++, when passing an array to a function, the array type is automatically converted to a pointer type, so what is actually passed is the address.

If you want to pass a one-dimensional array as a parameter in a function, you must declare the function formal parameter in one of the following three ways. The results of these three declaration methods are the same, because each method tells the compiler that an integer pointer will be received. Likewise, you can also pass a multidimensional array as a formal parameter.

Method 1

The formal parameter is a pointer:

void myFunction(int *param)
{
.
.
.
}

Method 2

The formal parameter is an array with a defined size:

void myFunction(int param[10])
{
.
.
.
}

Method 3

The formal parameter is an array of undefined size:

void myFunction(int param[])
{
.
.
.
}

Example

Now, let's look at the following function, which takes an array as a parameter and also passes another parameter. Based on the parameter passed, it returns the average of the elements in the array:

double getAverage(int arr[], int size) { int i, sum = 0; double avg; for (i = 0; i < size; ++i) { sum += arr[i]; } avg = double(sum) / size; return avg; }

Now, let's call the above function as follows:

Example

#include <iostream> using namespace std; // Function declaration double getAverage(int arr[], int size); int main () { // An integer array with 5 elements int balance[5] = {1000, 2, 3, 17, 50}; double avg; // Pass a pointer to an array as an argument avg = getAverage( balance, 5 ) ; // Output the return value cout << "The average is:" << avg << endl; return 0; }

When the above code is compiled and executed, it produces the following results:

平均值是: 214.4

You can see that, as far as the function is concerned, the length of the array is irrelevant, because C++ does not perform boundary checks on formal parameters.

C++ Arrays

other extensions