In C++, we can return a pointer to the base address(address of first element of array) of array from a function like any basic data type. However, C++ programming language does
not allow to return whole array from a function.
We should not return base pointer of a local array declared inside a function because as soon as control returns from a function all local variables gets destroyed. If we want to return a local array then we should declare it as a static variable so that it retains it's value after function call.
int* getScoreList();Above function returns the base address of an integer array.
C++ Program for Returning Array from a Function
#include <iostream> using namespace std; // This function returns an array of N even numbers int* getEvenNumbers(int N){ // Declaration of a static local integer array static int evenNumberArray[100]; int i, even = 2; for(i=0; i<N; i++){ evenNumberArray[i] = even; even += 2; } // Returning base address of evenNumberArray array return evenNumberArray; } int main(){ int *array, counter; array = getEvenNumbers(10); cout << "Even Numbers\n"; for(counter=0; counter<10; counter++){ cout << array[counter] << " "; } return 0; }Output
2 4 6 8 10 12 14 16 18 20Similarly, you can return multi dimentional arrays from a function.