Cpp Return Arrays From Function
# C++ Returning Arrays from Functions
[ C++ Arrays](#)
C++ does not allow returning a complete array as a function argument. However, you can return a pointer to an array by specifying the array name without an index.
If you want to return a one-dimensional array from a function, you must declare a function that returns a pointer, as follows:
int * myFunction(){//. . .}
Here is an example:
## Example
int* myFunction()
{
int myArray={1, 2, 3};
return myArray;
}
**Note:** You cannot simply return a pointer to a local array, because the local array will be destroyed when the function ends, and the pointer pointing to it will become invalid.
C++ does not support returning the address of a local variable outside the function unless the local variable is defined as a **static** variable.
To avoid the above situation, you can use a static array or dynamically allocate an array.
Using a static array requires creating a static array inside the function and returning its address, for example:
int* myFunction()
{
static int myArray={1, 2, 3};
return myArray;
}
Now, let's look at the following function, which generates 10 random numbers and uses an array to return them, as follows:
## Example
#include#include#includeusing namespace std; // Function to generate and return random numbers int * getRandom(){static int r; // Set the seed srand((unsigned)time(NULL)); for(int i = 0; i<10; ++i){r = rand(); cout<<r<<endl; }return r; }// Main function to call the above defined function int main(){// 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 result:
624723190146873569580711358597
YouTip