C++ 中将数组传递给函数


2022年9月4日, Learn eTutorial
1652

在本教程中,我们将通过示例演示如何在 C++ 中将一维多维数组作为函数参数传递。在 C++ 中,数组主要可以作为参数传递给函数。此外,函数可以返回数组。在学习将数组作为函数参数传递之前,请确保您理解 C++ 数组和 C++ 函数。

将数组传递给函数究竟是什么意思?

  • 数组可以像变量一样作为参数传递给函数。此外,函数可以返回数组。
  • 要将数组传递给函数,只需在函数调用期间提及数组名称即可。
  • 在学习将数组作为函数参数传递之前,请确保您理解 C++ 数组和 C++ 函数。为了更好地理解,请查阅我们之前的教程。

语法

在 C++ 中主要将数组传递给函数的语法


returnType functionName(dataType arrayName[arraySize]) {
// statement
}
 

例如


int total(int num[4]) {
// statement
}
 

在这种情况下,我们将一个名为 num 的 int 类型数组传递给 total() 函数。该数组的大小为 4。

使用数组作为参数的函数声明

有两种方法可以实现此目的:值传递和引用传递。

  1. 参数可以是一个数组。
    
    int sum(int arr[]);
     
    
  2. 或者,数组基地址的指针可以保留在参数列表中。
    
    int sum(int* ptr);
     
    

主要将单个数组传递给函数的示例

让我们创建一个非常基本的程序,其中 main() 函数声明并定义一个整数数组,并将数组的每个成员发送到一个只打印元素值的函数。


// Displaying a single array element using C++
#include <iostream>
using namespace std;
void arr(int a ) {
    // just display the array elements
        cout << "Numbers " << a <<endl;
}

int main() {
    // here we should declare as well as  initialize an array
    int myArr[] = {11, 12, 13};
    arr(myArr[1]); //just pass the array element myArr[1] only.

    return 0;
}

输出

Numbers 12

一个将一维数组传递给函数并进行解释的示例


// C++ Program to display roll numbers of 6 students
#include <iostream>
using namespace std;

// declare function in order to display the Roll Number & take a 1d array as parameter
void display(int a[6]) {
    cout << "Display The Roll Numbers: " << endl;

    // display array elements
    for (int i = 0; i < 6; ++i) {
        cout << "Student " << i + 1 << ": " << a[i] << endl;
    }
}
int main() {
    // declare and initialize an array
    int rollNum[6] = {41, 11, 73, 32,67,100};
    
    display(rollNum);    // call display function pass array as argument

    return 0;
}

输出

Display The Roll Numbers: 
Student 1: 41
Student 2: 11
Student 3: 73
Student 4: 32
Student 5: 67
Student 6: 100

让我们看看上面程序的运行情况

  1. 当主要通过将数组作为参数调用函数时,只使用数组名。
    
    void display(int m[6])
     
    

    在这种情况下,参数 rollNum 表示数组 rollNum[6] 的第一个元素的内存地址。

  2. 注意 display() 函数的参数。
    
    display(rollNum);
     
    

    在这种情况下,我们在函数参数中使用完整的数组声明,其中还包括方括号 []。

  3. int m[6] 被函数参数转换为 int* m。这将指向与数组 marks 指向的相同地址。因此,无论何时我们在函数体中更改 m[6],我们实际上都在更改原始数组 marks。这就是 C++ 管理向函数提供数组以节省内存和时间的方式。

为什么不能将数组的全部内容作为参数传递给 C++ 中的函数?

数组的全部内容不能作为参数传递给 C++ 中的函数。仅数组名,不带索引,允许您提供指向数组的指针。

您可以通过以下三种方法之一声明函数的形参,以将一维数组作为参数传递。所有三种声明过程都产生相同的结果,因为它们都通知编译器将接收一个整数指针。

  1. 方法 1:作为指针的形参如下
    void myFunction(int *param) {
    .
    .
    .
    }
     
    
  2. 方法 2:作为大小数组的形参如下
    void myFunction(int param[20]) {
    .
    .
    .
    }
    
  3. 方法 3:作为无大小数组的形参如下
    void myFunction(int param[]) {
    .
    .
    .
    }
    

现在考虑下面的函数,它将接受一个数组作为输入以及另一个参数。主要根据传递的参数,它将返回通过数组传递的数字的平均值,如下所示。


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;
}
 

接下来,让我们完全按照以下方式调用上述函数


#include <iostream>
using namespace std;
 
// function declaration:
double getAverage(int arr[], int size);

int main () {
   // an int array with 5 elements.
   int balance[5] = {1000, 2, 3, 17, 50};
   double avg;

   // pass pointer to the array as an argument.
   avg = getAverage( balance, 5 ) ;
 
   // output the returned value 
   cout << "Average value is: " << avg << endl; 
    
   return 0;
}

输出

Average value is: 214.4

如您所见,该方法不关心数组的长度,因为 C++ 不对形参进行任何边界检查。

一个将多维数组传递给函数并进行解释的示例。


#include <iostream>
using namespace std;

// just define a function 
// pass a 2 dimensional  array as a parameter
void display(int n[][3]) {
    cout << " The Displaying Values: " << endl;
    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 3; ++j) {
            cout << "num[" << i << "][" << j << "]: " << n[i][j] << endl;
        }
    }
}

int main() {

    // initialize 2d array
    int num[4][3] = {
        {8, 4},
        {9, 3},
        {5, 1}
    };

    // call the function
    // pass a 2d array as an argument
    display(num);

    return 0;
}

输出

The Displaying Values: 
num[0][0]: 8
num[0][1]: 4
num[0][2]: 0
num[1][0]: 9
num[1][1]: 3
num[1][2]: 0
num[2][0]: 5
num[2][1]: 1
num[2][2]: 0
num[3][0]: 0
num[3][1]: 0
num[3][2]: 0

上述程序中定义了一个名为 display() 的函数。该函数将接收一个二维数组。它接受 int n[][3] 的参数并输出内容,这意味着数组的元素。

我们在调用函数 (arr) 时只将二维数组的名称作为函数参数 display 传递。

C++ 中从函数返回数组

  • 函数返回一个包含要返回的数组基地址的指针,而不是数组本身。
  • 但是,我们必须确保数组在函数结束后仍然存在,这意味着它不能是函数局部的。
  • 函数也可以选择返回一个数组。然而,实际的数组并没有被返回。
  • 相反,指针用于返回数组第一个元素的地址。