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:
- Returning an array: