Alex Rivera | Logout

how to return two dimensional char array c++?

Asked 2009-04-06T09:05:45.903
10

i ve created two dimensional array inside a function, i want to return that array, and pass it somewhere to other function..

char *createBoard( ){  
  char board[16][10];
  int j =0;int i = 0;
  for(i=0; i<16;i++){
        for( j=0;j<10;j++){   
                board[i][j]=(char)201;
        }   
  }
  return board;
}

but this keeps giving me error

Edit
Report

2 Answers

2

I would really recommend using STL vector<> or boost/multi_array containers for this.

If you must use arrays, then I would recommend using a typedef to define the array.

typedef char[16][10] TBoard;

You could also return

 char**

...but then you would need to typecast it to the correct size in order to index it correctly. C++ does not support dynamic multiple dimension arrays.

Also as others have suggested you can't return an object on the stack (i.e., local variable)

answered 2009-04-06T09:17:32.770
1

Don't return pointer to a local variable, as other mentioned. If I were forced to do what you want to achieve, first I'd go for std::vector. Since you haven't learnt std::vector, here is another way:

void createBoard(char board[16][10])
{  
  int j =0;int i = 0;
  for(i=0; i<16;i++){
        for( j=0;j<10;j++){   
                board[i][j]=(char)201;
        }       
  }
}
answered 2009-04-06T10:05:49.783

Your Answer