Constructor
This is how I’m allocating it:
char **board = new char*[width];
for(i = 0; i < width; i++){
board[i] = new char[height];
for(j = 0; j < height; j++)
board[i][j] = 0;
}
this->board = &board;
Inside the class, it’s:
char ***board;
Destructor:
Now I want to delete it, so I wrote this (the board it the class field):
for(i = 0; i < width; i++)
delete (*board)[i];
delete (*board);
When running this:
Board* b = new Board(16, 30, 99);
delete b;
I get an Unhandled exception. Why?
You are storing a pointer to a variable on the stack, which becomes invalid as soon as the constructor returns. You should declare your class’s data member as
char **boardand assignthis->board = board.EDIT: See also @Kerrek SB’s comment. The local variable is redundant. Just use the data member directly (without the
this->).EDIT 2: Rectangular arrays are best created as a single array, using pointer arithmetic to index (which is what the compiler does with declared 2D arrays anyway):
This has the advantage of requiring just one memory allocation (and therefore one
delete[]). It also improves cache locality because the cells are contiguous.Even better, if you know the dimensions at compile-time, use templates:
This requires no memory allocation at all (other than the
new Board, of course).