function that returns an array c++ code example
Example 1: return array from function c++
#include <iostream>
using namespace std;
int* fun()
{
int* arr = new int[100];
arr[0] = 10;
arr[1] = 20;
return arr;
}
int main()
{
int* ptr = fun();
cout << ptr[0] << " " << ptr[1];
return 0;
}
Example 2: c++ function return array
#include <iostream>
#include <ctime>
using namespace std;
int * getRandom( ) {
static int r[10];
srand( (unsigned)time( NULL ) );
for (int i = 0; i < 10; ++i) {
r[i] = rand();
cout << r[i] << endl;
}
return r;
}
int main () {
int *p;
p = getRandom();
for ( int i = 0; i < 10; i++ ) {
cout << "*(p + " << i << ") : ";
cout << *(p + i) << endl;
}
return 0;
}