Home Creating a dynamic 2D array to store class objects
Reply: 1

Creating a dynamic 2D array to store class objects

Tony Cicero
1#
Tony Cicero Published in 2017-12-06 02:35:34Z

So I have a class called Cell, and I need to create a new Cell and put it into a 2d array. I believe the problem is how I created the 2D array. I have looked up how dynamic arrays work but I still can't find the problem. Below is some of my code and the first few errors I get

    Cell * board = new Cell[h]; //create new board
        for(int i = 0; i < h; i++){
            board[i] = new Cell[w];
            }
        for (int row = 0; row < h; row ++){     //initialize board
            for (int col = 0; col < w; col++){
                board[row][col] = new Cell; 
                board[row][col]->status = '#';
                board[row][col]->isCovered = true;
            }
        }

ERRORS:

minesweeper.h: In constructor ‘GameBoard::GameBoard(int, int, int)’:
minesweeper.h:29:17: error: no match for ‘operator=’ (operand types are 
‘Cell’ and ‘Cell*’)
    board[i] = new Cell[w];
             ^
minesweeper.h:29:17: note: candidate is:
minesweeper.h:4:8: note: Cell& Cell::operator=(const Cell&)
 struct Cell
    ^
minesweeper.h:4:8: note:   no known conversion for argument 1 from ‘Cell*’ 
to ‘const Cell&’
minesweeper.h:33:16: error: no match for ‘operator[]’ (operand types are 
‘Cell’ and ‘int’)
      board[row][col] = new Cell; 
            ^
minesweeper.h:34:16: error: no match for ‘operator[]’ (operand types are 
‘Cell’ and ‘int’)
      board[row][col]->status = '#';
                ^
sashang
2#
sashang Reply to 2017-12-06 02:41:16Z

Change the line

Cell* board = new Cell[h]

to

Cell** board = new Cell*[h]

Basically you want to create a 2d array, so you need to create and array of Cell pointers (new Cell*[h]). Then for each of those Cell pointers you want to allocate memory for each individual Cell. This is done in the loop:

for(int i = 0; i < h; i++){
    board[i] = new Cell[w];
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.310121 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO