1

I have been trying to program a Sudoku game in C++11. I have a Cell class which is used as a single square in a sudoku grid. The grid is encapsulated in the Sudoku class.

Here is the Sudoku class constructor:

Sudoku::Sudoku(int rows, int cols)
{
    this->setRows(rows);
    this->setCols(cols);

    this->grid = new Cell **[this->rows];

    unsigned int i, j;

    for (i = 0; i < this->rows; i++)
    {
        for (j = 0; j < this->cols; j++)
        {
            std::cout << "i: " << i << " j: " << j << std::endl;
            this->grid[i][j] = new Cell();
        }
    }

    this->populateGrid();
    this->hideCells();
}

And here is the Cell constructor:

Cell::Cell()
{

    this->number = 0;

    this->isHidden = false;
}

because of the print statement in the Sudoku constructor, I get the following output:

i: 0 j: 0
i: 0 j: 1
i: 0 j: 2
terminate called recursively

Important note: the Sudoku grid is initialised to be 10x10 cells. So I really don't know why it stops after creating the first 3 cells.

Thanks in advance to anyone who answers.

SOLUTION: Initialising each row of the grid helped solve the issue. Thanks to everyone who helped!

pab6750
  • 11
  • 2
  • 2
    You forgot to allocate memory for each row. See [How do you dynamically allocate a matrix?](https://stackoverflow.com/questions/1403150/how-do-you-dynamically-allocate-a-matrix) – Botje Oct 12 '21 at 09:08
  • Why do you have a grid of *pointers* to `Cell`? – molbdnilo Oct 12 '21 at 09:17
  • I would recommend starting with square boards of the conventional size before attempting more esoteric boards, like rectangular ones or not nine-by-nine. (How are you dividing a ten-by-ten board into ten ten-symbol parts?) – molbdnilo Oct 12 '21 at 09:28
  • Please show a [mre] – Alan Birtles Oct 12 '21 at 09:42
  • After `this->grid = new Cell **[this->rows];`, `grid` points to an array of uninitialized pointers. `grid[i]` then exhibits undefined behavior by way of accessing an uninitialized object. – Igor Tandetnik Oct 12 '21 at 14:24

0 Answers0