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?

Fox32
  • 13,126
  • 9
  • 50
  • 71
user2374842
  • 55
  • 1
  • 1
  • 2
  • 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: http://stackoverflow.com/questions/8617683/return-a-2d-array-from-a-function โ€“ Joe Bane May 12 '13 at 12:31
  • @Joe A `int**` wouldn't work here with no other changes because it is not layout compatible with a 2D array. โ€“ Joseph Mansfield May 12 '13 at 12:33
  • @sftrabbit Thanks. I just removed that part of my comment since I wasn't focused on that anyway. โ€“ Joe Bane May 12 '13 at 12:40

2 Answers2

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;
}
billz
  • 44,644
  • 9
  • 83
  • 100
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));
}
Community
  • 1
  • 1
David G
  • 94,763
  • 41
  • 167
  • 253