Returning Arrays from Functions in C++

To return an array from a function, pass it as a parameter in a function.

You can declare a function to return a primitive type value or an object. For example,

// Return the sum of the elements in the list

int sum(const int list[], size)

Can you return an array from a function using a similar syntax? For example, you may attempt to declare a function that returns a new array that is a reversal of an array, as follows:

// Return the reversal of list

int[] reverse(const int list[], int size)

This is not allowed in C++. However, you can circumvent this restriction by passing two array arguments in the function:

// newList is the reversal of list

void reverse(const int list[], int newList[], int size)

The program is given in Listing 7.7.

Listing 7.7 ReverseArray.cpp

1 #include <iostream>
2
using namespace std;
3
4
// newList is the reversal of list
5 void reverse(const int list[], int newList[], int size)
6 {
7   
for (int i = 0, j = size – 1; i < size; i++, j–)
8    {
9        newList[j] = list[i];
10    }
11 }
12
13
void printArray(const int list[], int size)
14 {
15   
for (int i = 0; i < size; i++)
16    cout << list[i] <<
” “;
17 }
18
19
int main()
20 {
21   
const int SIZE = 6;
22   
int list[] = {1, 2, 3, 4, 5, 6};
23   
int newList[SIZE];
24
25    reverse(list, newList, SIZE);
26
27    cout <<
“The original array: “;
28    printArray(list, SIZE);
29    cout << endl;
30
31    cout <<
“The reversed array: “;
32    printArray(newList, SIZE);
33    cout << endl;
34
35   
return 0;
36 }

The reverse function (lines 5-11) uses a loop to copy the first element, second, . . . , and so on in the original array to the last element, second last, . . . , in the new array, as shown in the following diagram:

To invoke this function (line 25), you have to pass three arguments. The first argument is the original array, whose contents are not changed in the function. The second argument is the new array, whose contents are changed in the function. The third argument indicates the size of the array.

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 *