Returning integer array from function with no arguments [duplicate]
Pretend you don't know what C-arrays are and join the world of modern C++:
#include <array>std::array<int, 8> getNums(){ std::array<int, 8> ret = {{ 1, 2, 3, 4, 5, 6, 7, 8 }}; return ret;}
If your compiler is too old to provide a std::
or std::tr1::
implementation of array<>
, consider using boost::array<>
instead. Or, consider using std::vector<>
either way.
I am led understand that when the function ends the pointer is lost, but will the array still be sent?
The behavior is undefined.
what is a good way to return this integer array with no arguments in the function call?
int nums[8];
num
is local variable which resides on stack. You cannot return the reference of a local variable. Instead alloc nums
with operator new
and remember to delete[]
it.
int* getNums(){ int *nums = new int[8] ; // ..... return nums ;}// You should deallocate the resources nums acquired through delete[] later,// else memory leak prevails.