How to Return a Local Array From a C++ Function?
Here, we will build a C++ program to return a local array from a function. And will come across the right way of returning an array from a function using 3 approaches i.e.
- Using Dynamically Allocated Array
- Using Static Array
- Using Struct
In function 'int* fun()': 6:8: warning: address of local variable 'arr' returned [-Wreturn-local-addr] int arr; ^
The above program is WRONG. It may produce values of 10 or 20 as output or may produce garbage values or may crash. The problem is, that we return the address of a local variable which is not advised as local variables may not exist in memory after the function call is over.
Following are some correct ways of returning an array
1. Using Dynamically Allocated Array
Dynamically allocated memory (allocated using new or malloc()) remains there until we delete it using the delete or free(). So we can create a dynamically allocated array and we can delete it once we come out of the function.
2. Using static Array
The lifetime of a static variable is throughout the program. So we can always create a local static array and return it.
3. Using struct
We can wrap the array in a structure/class and return an instance of the struct/class. The reason for this work is, that the array of members of structures is deeply copied. In the below program deep copy happens when we returned instance is copied in main.
Please Login to comment...