Returning local reference variable

How would you return a local array to main if local reference variables can’t be returned?

Hi @Equinoxx9, we cannot return a local array from a function back to main or to any other function. This is because the local variables may not exist in memory after current function call is over.
However in order to return an array we need to build it in pointer form AND NOT IN LOCAL FORM using:

int *arr ;
arr = new int[10] ;

An array created like this can be returned to functions. For this we need to change the return type of function also; from which we will return array.

So if you want to return an int array then your function definition should be:

int* <function_name> ( … ) {
        int *arr ;
        arr = new int[10] ;
        / *… Process array … /
        return arr ;
}


int main() {
        int
x;
        x = func();
        / *… Use the array now as you wish … */
}

Hope this helps :slight_smile: