在 C++ 中,我们可以将数组作为参数传递给函数。同样,我们也可以从函数返回数组。
在学习将数组作为函数参数传递之前,请确保您了解 C++ 数组 和 C++ 函数。
语法
将数组传递给函数的语法是:
returnType functionName(dataType arrayName[]) {
// code
}
示例 1:将一维数组传递给函数
// C++ Program to display marks of 5 students
#include <iostream>
using namespace std;
const int ARRAY_SIZE = 5;
// declare function to display marks
// take a 1d array as parameter
void display(int m[]) {
cout << "Displaying marks: " << endl;
// display array elements
for (int i = 0; i < ARRAY_SIZE; ++i) {
cout << "Student " << i + 1 << ": " << m[i] << endl;
}
}
int main() {
// declare and initialize an array
int marks[ARRAY_SIZE] = {88, 76, 90, 61, 69};
// call display function
// pass array as argument
display(marks);
return 0;
}
输出
Displaying marks: Student 1: 88 Student 2: 76 Student 3: 90 Student 4: 61 Student 5: 69
这里,
- 当我们通过将数组作为参数传递来调用函数时,只使用数组的名称。
这里,参数 marks 代表数组 marks[5] 的第一个元素的内存地址。display(marks);
- 但是,请注意
display()
函数的参数。
在这里,我们只期望一个整数数组。C++ 以这种方式处理将数组传递给函数,以节省内存和时间。void display(int m[])
将多维数组传递给函数
我们也可以将 多维数组 作为参数传递给函数。例如,
示例 2:将多维数组传递给函数
// C++ Program to display the elements of two
// dimensional array by passing it to a function
#include <iostream>
using namespace std;
// define a function
// pass a 2d array as a parameter
void display(int n[][2]) {
cout << "Displaying Values: " << endl;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 2; ++j) {
cout << "num[" << i << "][" << j << "]: " << n[i][j] << endl;
}
}
}
int main() {
// initialize 2d array
int num[3][2] = {
{3, 4},
{9, 5},
{7, 1}
};
// call the function
// pass a 2d array as an argument
display(num);
return 0;
}
输出
Displaying Values: num[0][0]: 3 num[0][1]: 4 num[1][0]: 9 num[1][1]: 5 num[2][0]: 7 num[2][1]: 1
在上面的程序中,我们定义了一个名为 display()
的函数。该函数将其参数作为二维数组 int n[][2]
,并打印数组的元素。
调用函数时,我们只将二维数组的名称作为函数参数 display(num)
传递。
注意:不必指定数组的行数。但是,列数应始终指定。这就是我们使用 int n[][2]
的原因。
我们也可以将多于 2 个维度的数组作为函数参数传递。
C++ 从函数返回数组
我们也可以从函数返回数组。但是,实际的数组不会被返回。而是通过 指针 返回数组第一个元素的地址。
我们将在后续教程中学习如何从函数返回数组。