Passing Arrays to Functions in C++

When an array argument is passed to a function, its starting address is passed to the array parameter in the function. Both parameter and argument refer to the same array.

Just as you can pass single values to a function, you also can pass an entire array to a func­tion. Listing 7.4 gives an example to demonstrate how to declare and invoke this type of function.

Listing 7.4 PassArrayDemo.cpp

1 #include <iostream>
2
using namespace std;
3
4
void printArray(int list[], int arraySize); // Function prototype
5
6
int main()
7 {
8   
int numbers[5] = {1, 4, 3, 6, 8};
9    printArray(numbers,
5); // Invoke the function
10
11   
return 0;
12 }
13
14
void printArray(int list[], int arraySize)
15 {
16   
for (int i = 0; i < arraySize; i++)
17    {
18        cout << list[i] <<
” “;
19    }
20 }

In the function header (line 14), int list[] specifies that the parameter is an integer array of any size. Therefore, you can pass any integer array to invoke this function (line 9). Note that the parameter names in function prototypes can be omitted. So, the function proto­type may be declared without the parameter names list and arraySize as follows:

void printArray(int [], int); // Function prototype Note

C++ uses pass-by-value to pass array arguments to a function. There are important dif­ferences between passing the values of variables of primitive data types and passing arrays.

  • For an argument of a primitive type, the argument’s value is passed.
  • For an argument of an array type, the value of the argument is the starting mem­ory address to an array; this value is passed to the array parameter in the function. Semantically, it can be best described as pass-by-sharing, that is, the array in the function is the same as the array being passed. Thus, if you change the array in the function, you will see the change outside the function. Listing 7.5 gives an example that demonstrates this effect.

Listing 7.5 EffectOfPassArrayDemo.cpp

1 #include <iostream>
2
using namespace std;
3
4
void m(int, int []);
5

6 int main()
7 {
8   
int x = 1; // x represents an int value
9    int y[10]; // y represents an array of int values
10   y[0] = 1; // Initialize y[0] 11
12   m(x, y);
// Invoke m with arguments x and y
13
14   cout <<
“x is ” << x << endl;
15   cout <<
“y[0] is ” << y[0] << endl;
16
17   
return 0;
18 }
19
20
void m(int number, int numbers[])
21 {
22    number =
1001; // Assign a new value to number
23    numbers[0] = 5555; // Assign a new value to numbers[0] 24 }

You will see that after function m is invoked, x remains 1, but y[0] is 5555. This is because the value of x is copied to number, and x and number are independent variables, but y and numbers reference to the same array. numbers can be considered as an alias for array y.

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *