Can I return an array by value in C++? By value I mean returning a copy instead of using a pointer. If so can someone provide an example of returning a 1d array and a 2d array?
3 Answers
No; you can return arrays by value only by wrapping them inside a struct or a class (actually, you can simply return an appropriate instance of std::array, which encapsulates a C-style array inside a template class which provides also some bells and whistles).
4 Comments
std::vector would work as well (if the OP doesn't have TR1 or C++11 libraries)std::array can (and more as you've rightly mentioned). I was just listing an alternative in case the OP didn't have access to std::arrayNo this is not allowed in C/C++ .
You can return array by reference, if it's not local to function. The other work around is to wrap it inside a 'struct/class' wrapper and return its object.
1 Comment
No this is impossible, unless you use some kind of custom array class (such as std::array as mentioned by Matteo Italia). Arrays in C/C++ are treated in much the same way as pointers.