Returning local arrays

whenever we are returning a local array aren’t we copying that local array to the variable calling that function?? so why is it giving garbage value instead of the value at that index??

Hello @gulatigarvita08,

As it is explained in the videos of Dynamic Programming:

  1. Suppose you create an array, a local one inside a function and then returning it’s address (or returning the array).

  2. when you’ll make a call to this function, a space min the call stack called stack frame is assigned to this function call.

  3. The local array will be assigned memory inside that stack frame.

  4. So, as soon as it will execute the return statement, the compiler will deallocate the stack frame assigned to this function call and hence, the memory assigned to this local array will be freed.

Now, the question arises, How can you return the address of something that do not even exists.

Thus, the variable is assigned a random address due to this deallocation and hence, producing the garbage value.

hope, this would help.
Give a like if you are satisfied.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.