尝试填充时,2d-Array失败

时间:2017-04-26 22:14:53

标签: c++ arrays multidimensional-array

我正在写一个最终将解决8-Queen拼图的课程。我添加了一个名为populate的测试方法,以确保我正确地创建了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;
}

1 个答案:

答案 0 :(得分:3)

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

board[size] = new int[size];

可能,你希望这是

board[i] = new int[size];