Returning a Pointer from Functions in C++

A C++function may return a pointer.

You can use pointers as parameters in a function. Can you return a pointer from a function? Yes, you can.

Suppose you want to write a function that passes an array argument, reverses it, and returns the array. You can define a reverse function and implement it as shown in Listing 11.6.

Listing 11.6 ReverseArrayUsingPointer.cpp

1 #include <iostream>
2
using namespace std;
3
4
int* reverse(int* list, int size)
5 {
6   
for (int i = 0, j = size – 1; i < j; i++, j–)
7    {
8       
// Swap list[i] with list[j] 9        int temp = list[j];
10       list[j] = list[i];
11       list[i] = temp;
12   }
13
14   
return list;
15 }
16
17
void printArray(const int* list, int size)
18 {
19   
for (int i = 0; i < size; i++)
20    cout << list[i] <<
” “;
21 }
22
23
int main()
24 {
25   
int list[] = {1, 2, 3, 4, 5, 6};
26   
int* p = reverse(list, 6);

27    printArray(p, 6);
28
29   
return 0;
30 }

The reverse function prototype is specified like this:

int* reverse(int* list, int size)

The return value type is an int pointer. It swaps the first element with the last, second ele­ment with the second last, . . . , and so on in list, as shown in the following diagram:

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 *