How to return local array from a C++ function?


A local array cannot be directly returned from a C++ function as it may not exist in memory after the function call. A way to resolve this is to use a static array in the function. As the lifetime of the static array is the whole program, it can easily be returned from a C++ function without the above problem.

A program that demonstrates this is given as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
int *retArray() {
   static int arr[10];
   for(int i = 0; i<10; i++) {
      arr[i] = i+1;
   }
   return arr;
}
int main() {
   int *ptr = retArray();
   cout <<"The array elements are: ";
   for(int i = 0; i<10; i++) {
      cout<< ptr[i] <<" ";
   }
   return 0;
}

Output

The output of the above program is as follows.

The array elements are: 1 2 3 4 5 6 7 8 9 10

Now let us understand the above program.

In the function retArray(), a static array arr is defined. Then a for loop is used to initialize this array. Finally array arr is returned. The code snippet that shows this is as follows.

int *retArray() {
   static int arr[10];
   for(int i = 0; i<10; i++) {
      arr[i] = i+1;
   }
   return arr;
}

In the main() function, the function retArray() is called and ptr points to the start of the array arr. The array elements are displayed using a for loop. The code snippet that shows this is as follows.

int main() {
   int *ptr = retArray();
   cout <<"The array elements are: ";
   for(int i = 0; i<10; i++) {
      cout<< ptr[i] <<" ";
   }
   return 0;
}

Updated on: 26-Jun-2020

586 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements