1

I was wondering how I can return a 2d array in my function. My code is something like this:

int[][] function ()
{
    int chessBoard[x][x];
    memset(chessBoard,0,x*x*sizeof(int));
    return chessBoard;      
}

I get the error message: "error: unexpected unqualified-id before '[' token" on my first line. Any tips on how I can get my function to work properly?

3
  • You have a bigger problem: your 2D array is allocated on stack memory. You don't want to return (a pointer to) that (you should copy it or use heap memory or encapsulate it). Related: stackoverflow.com/questions/8617683/… Commented May 12, 2013 at 12:31
  • @Joe A int** wouldn't work here with no other changes because it is not layout compatible with a 2D array. Commented May 12, 2013 at 12:33
  • @sftrabbit Thanks. I just removed that part of my comment since I wasn't focused on that anyway. Commented May 12, 2013 at 12:40

2 Answers 2

1

Use vector of vector instead:

template<typename T, size_t N>
std::vector<std::vector<T> > func()
{
  std::vector<std::vector<T>> data(N, std::vector<T>(N));
  return data;
}

int main ( int argc, char ** argv)
{
  std::vector<std::vector<int> > f = func<int, 10>();   
  return 0;
}

If you are using C++11, you could try with std::array:

template<typename T, size_t N>
std::array<std::array<T, N>, N> func()
{
  return  std::array<std::array<T, N>, N>();
}

int main ( int argc, char ** argv)
{
  auto f = func<int, 10>();   
  return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Unfortunately, arrays cannot be returned from functions. It is clearly stated in the Standard.

C++11 Standard § 8.3.5 Functions

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.

But modern C++ practices advise that you use STL containers to facilitate the confusing syntax and memory allocation. In your particular setup, we can replace your C-style arrays with a std::vector:

std::vector< std::vector<int> > function()
{
    return std::vector< std::vector<int> >(x, std::vector<int>(x));
}

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.