Latest web development tutorials

C ++ to pass an array to a function

C ++ Array C ++ Array

C ++ does not allow to pass a complete array as a parameter to a function, however, you can specify the array name without an index to pass a pointer to an array.

If you want to pass a one-dimensional array in a function as an argument, you must be in the following three ways to declare a function in the form of parameters, the results of these three statements is the same way, because each way will tell the compiler to receive a integer pointer. Similarly, you can also pass a multidimensional array as a formal parameter.

Mode 1

Formal parameter is a pointer:

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

Mode 2

Formal parameter is a defined array size:

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

Mode 3

Formal parameter is an array of undefined size:

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

Examples

Now, let's look at the following function that the array as a parameter, and also passed another parameter, according to the preaching of the parameters, the average return for each element 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:

#include <iostream>
using namespace std;
 
// 函数声明
double getAverage(int arr[], int size);

int main ()
{
   // 带有 5 个元素的整型数组
   int balance[5] = {1000, 2, 3, 17, 50};
   double avg;

   // 传递一个指向数组的指针作为参数
   avg = getAverage( balance, 5 ) ;
 
   // 输出返回值
   cout << "平均值是:" << avg << endl; 
    
   return 0;
}

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

平均值是: 214.4

You can see it in terms of function, length of the array does not matter, because C ++ does not perform bounds checking on the form parameters.

C ++ Array C ++ Array