C++ allows us to return the arrays from a function. However the actual array values cannot be returned, so we return the array from the function with the help of pointers.
Pointers are the variables that hold an address. With the help of pointers, the address of the first element is returned from a function. The name of the array is itself points to the first element.
In order to return the array from the function, we need to declare a function returning a pointer in a one-dimensional array. Example: syntax of returning function
1 2 3 4 5 | data-type * function_name() { ..... ..... ..... } |
Also, C++ does not allow to return the address of the local variable from the function, so we need to declare the local variable as static in a function.
Example of C++ Return Array from Functions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #include <iostream> using namespace std; int *return_func() { // static declaration of array static int arr[10]; for (int i = 0; i < 10; i++) { arr[i] = i; } //address of array returned return arr; } int main() { //pointer declaration int *ptr; ptr = return_func(); //address of a cout << "Printing an returned array: " << endl; for (int i = 0; i < 10; i++) cout << ptr[i] << " "; //ptr[i] = *(ptr + i) return 0; } |
Output:
1 2 | Printing an returned array: 0 1 2 3 4 5 6 7 8 9 |