Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return two dimensional char array c++?

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

like image 981
r4ccoon Avatar asked Apr 06 '09 09:04

r4ccoon


1 Answers

Yeah see what you are doing there is returning a pointer to a object (the array called board) which was created on the stack. The array is destroyed when it goes out of scope so the pointer is no longer pointing to any valid object (a dangling pointer).

You need to make sure that the array is allocated on the heap instead, using new. The sanctified method to create a dynamically allocated array in modern C++ is to use something like the std::vector class, although that's more complicated here since you are trying to create a 2D array.

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

    return board;
}

void freeBoard(char **board)
{
    for (int i=0; i<16; i++)
      delete [] board[i];
    delete [] board;
}
like image 56
1800 INFORMATION Avatar answered Nov 02 '22 09:11

1800 INFORMATION