How to return an array from a function in C++?


C++ does not return entire array but it can return pointer to an array. Outside the function, address of local variable cannot be returned. By making local variable static, it can return the address of local variable.

The following is the syntax to return a pointer.

int * function_name()
{ body }

Here,

function_name − The name of function given by user.

The following is an example to return an array from a function.

Example

 Live Demo

#include <iostream>
using namespace std;
int * ret() {
   static int x[3];
   for(int i=0 ; i<5 ; i++) {
      cout << " " <<&x[i];
   }
   return x;
}
int main() {
   ret();
   return 0;
}

Output

0x601180 0x601184 0x601188 0x60118c 0x601190

In the above program, a function ret() is created and it is returning an array. A static int type array is declared and addresses of allocated memory blocks are printed.

int * ret() {
   static int x[3];
   for(int i=0 ; i<5 ; i++) {
      cout << " " <<&x[i];
   }
   return x;
}

In the main() function, the function ret() is called −

ret();

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

300 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements