C++ Tutorial C++ Advanced C++ References

C++ - Returning an array from a function



C++ does not allow to return an entire array from a function. However, a pointer to an array can be returned by specifying the array's name without an index.

Consider a function called MyFunction which returns pointer to an array, the following syntax can be used:

Syntax

//returns pointer to 1-D array of type int
int * MyFunction() {
  statements;
}

//returns pointer to 2-D array of type int
int** MyFunction() {
  statements;
}

Example: returning a 1-D array

Consider the example below which generate 10 random numbers between 1 and 1000 and return them using an array.

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

//function to generate and return 10 
//random numbers between 1 and 1000
int * getRandomVector() {

  static int rand_vec[10];

  //initialize random seed
  srand (time(NULL));
   
  for(int i = 0; i < 10; ++i) {
    rand_vec[i] = rand() % 1000 + 1;
    cout<<rand_vec[i]<<endl;
  }

   return rand_vec;
}


int main () {
  //a pointer to an int
  int *p;

  p = getRandomVector();
   
  for(int i = 0; i < 10; i++) {
    cout<<"*(p + "<<i<<") : ";
    cout<<*(p + i)<<endl;
  }

  return 0;
}

The output of the above code will be similar to:

223
854
278
752
223
771
149
17
959
231
*(p + 0) : 223
*(p + 1) : 854
*(p + 2) : 278
*(p + 3) : 752
*(p + 4) : 223
*(p + 5) : 771
*(p + 6) : 149
*(p + 7) : 17
*(p + 8) : 959
*(p + 9) : 231

Example: returning a 2-D array

Consider the example below which demonstrates how to return a pointer to a 2-D array from a function.

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

//function to generate and return a 2-D array 
//containing random numbers between 1 and 1000
int** getRandomMatrix(int height, int width) {

  int** rand_matrix = 0;
  rand_matrix = new int*[height];

  //initialize random seed
  srand (time(NULL));
   
  for(int i = 0; i < height; ++i) {
    
    rand_matrix[i] = new int[width];
    for(int j = 0; j < width; ++j) {
      rand_matrix[i][j] = rand() % 1000 + 1;
    }
  }

   return rand_matrix;
}

int main () {
  int height = 3;
  int width = 3;

  int **p = getRandomMatrix(height, width);

  for(int i = 0; i < height; ++i) {
    for(int j = 0; j < width; ++j) {
      cout<<p[i][j]<<" ";
    }
    cout<<endl;
  }  

  return 0;
}

The output of the above code will be similar to:

714 604 209 
427 924 888 
681 581 890 

❮ C++ - Arrays

5