Explain how this C++ function returns an array -


i found code online http://www.cplusplus.com/forum/beginner/6644/#msg30551 supposed return array c++ function. explanation illustrating how function operates respect memory allocation, stacks, heaps, pointers etc.

int *f(size_t s){     int *ret=new int[s];     (size_t a=0;a<s;a++)         ret[a]=a;     return ret; } 

i.

int *ret=new int[s]; 

1. allocate memory ret on stack - int pointer
2. allocate continuous memory size s * sizeof(int) on heap
3. make ret point first element of allocated memory (from 2.)


ii.

for (size_t a=0;a<s;a++)     ret[a]=a; 
  1. allocates memory on stack a
  2. loop through allocated memory in i., assigning values each element
  3. after end of for-statement, a no longer accessible (it's available in for)

iii.

return ret; 

return a copy of ret pointer, points first element of created in i. array, initialized in ii.

after return, ret "destroyed".


the caller of function must not forget deallocate (free) memory, invoking delete[].

for example:

int * my_array = f( 6 ); // sth my_array delete[] my_array; 

Comments