您可以将数组作为参数传递给函数,就像将变量作为参数传递一样。为了将数组传递给函数,您只需要在函数调用中提及数组名称,如下所示:
function_name(array_name);
示例:将数组传递给函数
在这个例子中,我们传递两个数组a和b到函数sum()。此函数相加两个数组的相应元素并显示它们。
#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;}输出:
1122334455
示例 2:将多维数组传递给函数
在这个例子中,我们将多维数组传递给函数square,该函数显示每个元素的平方。
#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;}输出:
149162536
