多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# 在 C++ 中将数组传递给函数 > 原文: [https://beginnersbook.com/2017/08/cpp-passing-array-to-function/](https://beginnersbook.com/2017/08/cpp-passing-array-to-function/) 您可以将[数组](https://beginnersbook.com/2017/08/cpp-arrays/)作为参数传递给函数,就像将变量作为参数传递一样。为了将数组传递给函数,您只需要**在函数调用**中提及数组名称,如下所示: ```cpp function_name(array_name); ``` ## 示例:将数组传递给函数 在这个例子中,我们传递两个数组`a`和`b`到函数`sum()`。此函数相加两个数组的相应元素并显示它们。 ```cpp #include <iostream> using namespace std; /* This function adds the corresponding  * elements of both the arrays and  * displays it.  */ void sum(int arr1[], int arr2[]){ int temp[5]; for(int i=0; i<5; i++){ temp[i] = arr1[i]+arr2[i]; cout<<temp[i]<<endl; } } int main(){ int a[5] = {10, 20, 30, 40 ,50}; int b[5] = {1, 2, 3, 4, 5}; //Passing arrays to function sum(a, b); return 0; } ``` **输出:** ```cpp 11 22 33 44 55 ``` ## 示例 2:将多维数组传递给函数 在这个例子中,我们将[多维数组](https://beginnersbook.com/2017/08/cpp-multidimensional-arrays/)传递给函数`square`,该函数显示每个元素的平方。 ```cpp #include <iostream> #include <cmath> using namespace std; /* This method prints the square of each  * of the elements of multidimensional array  */ void square(int arr[2][3]){ int temp; for(int i=0; i<2; i++){ for(int j=0; j<3; j++){ temp = arr[i][j]; cout<<pow(temp, 2)<<endl; } } } int main(){ int arr[2][3] = {        {1, 2, 3},       {4, 5, 6} }; square(arr); return 0; } ``` **输出:** ```cpp 1 4 9 16 25 36 ```