2D阵列试图填充时失败

2d-Array fails when trying to populate

本文关键字:失败 填充 阵列 2D      更新时间:2023-10-16

我正在编写一个最终将解决8年拼图的课程。我添加了一个名为pupulate的测试方法,以确保正确和动态分配内存正确创建2D数组,但是当该方法称为程序崩溃时,当我调试以下Visual Studio错误时,请弹出:

Exception thrown at 0x01281DFB in 8Queen.exe: 0xC0000005: Access violation writing location 0xCDCDCDCD.
If there is a handler for this exception, the program may be safely continued.

我的构造函数:

Queen::Queen(int s)
{
    size = s;
    board = new int *[size];
    for (int i = 0; i < size; ++i)
        board[size] = new int[size];
}

我的填充方法:

void Queen::populate()
    {
        for (int i = 0; i < size; ++i)  // for each row
            for (int j = 0; j < size; ++j) // for each column
                board[i][j] = 1;
    }

我的解构:

Queen::~Queen()
{
    for (int i = 0; i < size; i++)
        delete[] board[i];
    delete[] board;
}

我的主要:

int main()
{
    fm::Queen board(10);
    board.populate();
    board.printBoard();
    return 0;
}

在您的构造函数中,您有以下行:

board[size] = new int[size];

可能,您希望这是

board[i] = new int[size];