在 C++ 编程中将数组传递给函数

在本教程中,我们将通过示例学习如何在 C++ 中将一维和多维数组作为函数参数传递。

在 C++ 中,我们可以将数组作为参数传递给函数。而且,我们还可以从函数中返回数组。

在了解将数组作为函数参数传递之前,请确保您了解 C++ 数组和 C++ 函数。


将数组作为函数参数传递的语法

将数组传递给函数的语法是:

returnType functionName(dataType arrayName[arraySize]) {
    // code
 我们来看一个例子,

int total(int marks[5]) {
    // code
 在这里,我们传递了一个 int 类型数组名为 marks 到函数 total() .数组的大小为 5 .


示例1:将一维数组传递给函数

// C++ Program to display marks of 5 students
#include <iostream>
using namespace std;
// declare function to display marks
// take a 1d array as parameter
void display(int m[5]) {
    cout << "Displaying marks: " << endl;
    // display array elements    
    for (int i = 0; i < 5; ++i) {
        cout << "Student " << i + 1 << ": " << m[i] << endl;
int main() {
    // declare and initialize an array
    int marks[5] = {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

在这里,

  1. 当我们通过传递一个数组作为参数调用函数时,只使用数组的名称。
    display(marks);
    这里,参数 marks 表示数组marks[5]的第一个元素的内存地址 .
  2. 但是,请注意 display() 的参数 功能。
    void display(int m[5])
    这里,我们在函数参数中使用数组的完整声明,包括方括号[] .
  3. 函数参数int m[5] 转换为 int* m; .这指向数组 marks 指向的相同地址 .这意味着当我们操作 m[5] 在函数体中,我们实际上是在操作原始数组 marks .

    C++ 以这种方式处理将数组传递给函数以节省内存和时间。

将多维数组传递给函数

我们还可以将多维数组作为参数传递给函数。例如,

示例 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++ 从函数返回数组

我们也可以从函数返回一个数组。但是,不会返回实际数组。而是通过指针返回数组第一个元素的地址。

我们将在接下来的教程中学习如何从函数中返回数组。


数组是一种数据结构,可以存储相同类型元素的固定大小的顺序集合。数组用于存储数据的集合,但通常将数组视为相同类型变量的集合会更有用。 不用声明单独的变量,例如 number0、number1、...和 ​​number99,而是声明一个数组变量,例如 numbers,并使用 numbers[0]、numbers[1] 和 ...、numbers[99] 来表示个体变量。通过索引访问数组中的特定元素。 所有数组都由连续的内存位置组成。最低地址对应第一个元素,最高地址对应最后一个元素。 声明数组 为了在 C 中声明一个数组,程序员指定元素的类型和数组所需的元素数量如下 - type arr