I have to do Conway's Game of Life. I need to create a 20x80 board using a dynamic array (institutional requirements).
const int ROWS = 20
const int COLUMNS = 80
void createBoard(char board[ROWS][COLUMNS]){
for(int i = 0; i < ROWS; i ){
for(int j = 0; j < COLUMNS; j ){
board[i][j] = ' ';
}
}
cout << "Created board" << endl;
}
I managed to create this board, but i'm not using a dynamic array here.
I know that to create a dynamic array i have to do the following:
char *array = new char[size];
But how i would implement the dynamic array in the for loop? I cant get my head around on how to convert the alredy made function createBoard
into a dynamic array
CodePudding user response:
In the following code snippet function createBoard
dynamically allocates and initializes the board as 2D array in row-major order.
Function deleteBoard
deallocates the board.
const int ROWS = 20;
const int COLUMNS = 80;
char ** createBoard( void )
{
//allocate array of pointers to board's rows
char ** board = new char *[ ROWS ];
for( int rowIdx = 0; rowIdx < ROWS; rowIdx ){
//allocate board's rowIdx-th row
board[ rowIdx ] = new char[ COLUMNS ];
//initialize content of allocated row
for( int columnIdx = 0; columnIdx < COLUMNS; columnIdx )
board[ rowIdx ][ columnIdx ] = ' '; //accessing element at rowIdx-th row and columnIdx-th columns
}
return board;
}
void deleteBoard( char ** aBoard )
{
//dealocate every row
for( int rowIdx = 0; rowIdx < ROWS; rowIdx )
delete [] aBoard[ rowIdx ];
//deallocate array of pointers to board's rows
delete [] aBoard;
}