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

C++ProgrammingServer Side Programming

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();
raja
Published on 08-Nov-2018 10:34:25
Advertisements