首页 > 代码库 > 将数组传递给函数

将数组传递给函数

 1 #include <iostream>
 2 #include <iomanip>
 3 using namespace std;
 4 
 5 void modifyArray(int [], int);
 6 void modifyElement(int);
 7 
 8 int main()
 9 {
10     const int arraySize = 5;
11     int a[arraySize] = {0, 1, 2, 3, 4};
12 
13     cout << "Effects of passing entire array by reference : "
14         << "\n\nThe values of the original array are:\n";
15 
16     for (int i = 0; i < arraySize; i++)
17     {
18         cout << setw(3) << a[i];
19     }
20     cout << endl;
21 
22     modifyArray(a, arraySize);
23     cout << "The values of the modified array are : \n";
24     
25     for (int j = 0; j < arraySize; j++)
26     {
27         cout << setw(3) << a[j];
28     }
29 
30     cout << "\n\nEffects of passing array element by value : "
31         << "\n\na[3] before modifyElement: " << a[3] << endl;
32 
33     modifyElement(a[3]);
34     cout << "a[3] after modifyElement : " << a[3] << endl;
35 }
36 
37 void modifyArray(int b[], int sizeOfArray)
38 {
39     for (int k = 0; k < sizeOfArray; k++)
40     {
41         b[k] *= 2;
42     }
43 }
44 
45 void modifyElement(int e)
46 {
47     cout << "Value of element in modifyElement: " << (e *= 2) << endl;
48 }