C + + does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array ' s name without an index.
If you want to return a single-dimension array from a function, you would has to declare a function returning a pointer a s in the following example:
int* myFunction(){
.
.
.
}
Second point to remember are that C + + does not advocate to return the address of a local variable to outside of the Functio n so you would has to define the local variable as? staticvariable.
Now, consider the following function, which'll generate random numbers and return them using an array and call this F Unction as follows:
#include<iostream>
#include<ctime>
?
Usingnamespace std;
?
function to generate and retrun random numbers.
int* getrandom(){
Staticint r[ten];
?
Set the seed
Srand ((unsigned)time( NULL ) );
?????
for ( int I = 0 ; I < 10 ; ++ i Span style= "COLOR: #666600" >) {
R [i] = rand();
cout << R [i] << endl;
}
?
return R ;
}
?
Main function to call above defined function.
int Main (){
A pointer to an int.
int*P;
?
P = Getrandom ();
?????
for ( int I = 0 ; I < 10 ; I ++ {
cout << " * (P + " << I Span style= "COLOR: #666600" ><< ;
cout << * (P + i)<< endl;
}
?
return0;
}
When the above code is compiled together and executed, it produces result something as follows:
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
Return array from functions in C + +