1

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 3

6

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).

Sign up to request clarification or add additional context in comments.

4 Comments

std::vector would work as well (if the OP doesn't have TR1 or C++11 libraries)
@Praetorian: but it is a completely different thing (more powerful, but with some overhead and overkill for several tasks).
It is different, but it can do everything 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::array
@Praetorian: sure, I was just pointing out that it's not exactly what he asked. :)
1

No 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

How would I return an array by reference?
1

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.

6 Comments

No. Arrays in C and C++ are not pointers. They decay to pointers in many occasions, but they are a different beast. Have a look at the array FAQ.
How is it not effectively a pointer that is allocated automatically? If you could provide a link to a document concerning this it would be appreciated.
You can read the C or C++ standard (where you'll see that arrays and pointers are separated types with different rules), or the aforementioned FAQ.
When your comment was first posted the link was not included. I do see that my initial comment about them being the exact same is wrong, however they behave in much the same way and in almost all cases can be treated as the same.
@jli this thread (among plenty of others) contains discussion about the topic and parts of the standard that Matteo mentioned.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.