c++ method code that returns an array from a function

  • 2020-06-23 01:38:48
  • OfStack

How does c++ return an array from a function?

C++ returns an array from a function

C++ is not allowed to return an entire array as an argument to a function. However, you can return a pointer to the array by specifying the name of the unindexed array.

If you want to return a 1-dimensional array from a function, you must declare a function that returns a pointer, as follows:


int * myFunction()

{

.

.

.

}

In addition, C++ does not support returning the address of a local variable outside a function unless the local variable is defined as static.

Now, let's look at the following function, which generates 10 random Numbers and returns them using an array, as follows:

The instance


#include <iostream>

#include <cstdlib>

#include <ctime>

 

using namespace std;

 

//  Functions to generate and return random Numbers 

int * getRandom( )

{

 static int r[10];

 

 //  Set the seeds 

 srand( (unsigned)time( NULL ) );

 for (int i = 0; i < 10; ++i)

 {

  r[i] = rand();

  cout << r[i] << endl;

 }

 

 return r;

}

 

//  To call the main function that defined the function above 

int main ()

{

  // 1 A pointer to an integer 

  int *p;

 

  p = getRandom();

  for ( int i = 0; i < 10; i++ )

  {

    cout << "*(p + " << i << ") : ";

    cout << *(p + i) << endl;

  }

 

  return 0;

}

When the above code is compiled and executed, it produces the following results:


624723190

1468735695

807113585

976495677

613357504

1377296355

1530315259

1778906708

1820354158

667126415

*(p + 0) : 624723190

*(p + 1) : 1468735695

*(p + 2) : 807113585

*(p + 3) : 976495677

*(p + 4) : 613357504

*(p + 5) : 1377296355

*(p + 6) : 1530315259

*(p + 7) : 1778906708

*(p + 8) : 1820354158

*(p + 9) : 667126415

That's how c++ returns an array from a function, and if you have anything to add you can contact this site.


Related articles: