How to return local variables from a function in C++
What happens when you try to return a local variable as usual?
For example, in the following code, when the array is created inside a function and returned to the caller function, it throws a runtime error as the array was created in the stack memory, and therefore it is deleted once the function ends.
Segmentation Fault (SIGSEGV)
How to return a local variable from a function?
But there is a way to access the local variables of a function using pointers, by creating another pointer variable that points to the variable to be returned and returning the pointer variable itself.
- Returning a local variable:
Note : Here, pointers works because the normal variables get stored in the stack which get destroyed after function ends. But, the pointers get stored in the heap and remain even after the fun call get over. So, we are able to access the value.
- Returning an array: