C++数组名作函数参数

在C++中,可以将数组名作为函数参数传递给函数。这可以通过指针或引用来实现。当数组名作为函数参数时,它会被转换为指向其首元素的指针。

使用指针作为函数参数

#include <iostream>
using namespace std;

// 示例函数,接受一个整数数组的指针和数组的大小
void processArray(int *arr, int size) {
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

int main() {
    int myArray[] = {1, 2, 3, 4, 5};
    processArray(myArray, 5); // 将数组名作为函数参数传递
    return 0;
}

使用引用作为函数参数

#include <iostream>
using namespace std;

// 示例函数,接受一个整数数组的引用
void processArray(int (&arr)[5]) {
    for (int i = 0; i < 5; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

int main() {
    int myArray[] = {1, 2, 3, 4, 5};
    processArray(myArray); // 将数组名作为函数参数传递
    return 0;
}

在这两个示例中,processArray 函数分别使用了指针和引用来接受数组作为参数。无论哪种方式,传递数组名都可以使函数对数组进行操作。

使用数组名作为函数参数求解3x4矩阵中的最大值:

#include <iostream>
using namespace std;

// 使用引用作为函数参数
int findMax(int (&arr)[3][4]) {
    int maxVal = arr[0][0];
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 4; j++) {
            if (arr[i][j] > maxVal) {
                maxVal = arr[i][j];
            }
        }
    }
    return maxVal;
}

int main() {
    int matrix[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
    int max = findMax(matrix);
    cout << "The maximum value in the matrix is: " << max << endl;
    return 0;
}

在这个示例中,findMax 函数使用引用来接受一个3x4的整数矩阵作为参数,并找到其中的最大值。main 函数中声明了一个3x4的整数矩阵,并调用 findMax 函数来获取最大值并打印出来。

  • 12
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值