0

I want to create a function that returns a C-style multidimensional array
int mArray[2][2]; int[][] mArray getArray();

so this does not work, and I don't know why. Any help would be appreciated.

3
  • 1
    Even if you fiddle around and get the right syntax, you can't have a built-in array as a return type. Commented Aug 6, 2015 at 21:43
  • 3
    It may help this question if you explain your ultimate goal. Are you trying to trying to return a "grid" of ints? Are you trying to implement an interface that's C-compatible? Are you interested in learning about the dusty corners of C++ syntax? Commented Aug 6, 2015 at 21:46
  • 1
    I cannot upvote @DrewDormann 's comment enough. Even if what you are asking is impossible, there are almost always alternatives. Commented Aug 6, 2015 at 22:13

2 Answers 2

5

From [dcl.funct]:

Functions shall not have a return type of type array or function, although they may have a return type of type pointer or reference to such things. There shall be no arrays of functions, although there can be arrays of pointers to functions.

You can, however, return a std::array instead:

std::array<std::array<int, 2>, 2> getArray();
Sign up to request clarification or add additional context in comments.

Comments

2

You cannot return arrays by value because they do not copy implicitly (and because the standard says so). You should use std::array instead:

std::array<std::array<int,2>,2> fun();
std::array<std::array<int,2>,2> arr = fun();

There are not many reasons to use C-arrays over std::array nowadays, with the most common one probably being "because my teacher/prof/boss says so".

Comments

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.