gpt4 book ai didi

c++ - 二维数组在尝试填充时失败

转载 作者:行者123 更新时间:2023-11-27 23:54:30 25 4
gpt4 key购买 nike

我正在编写一个最终将解决 8 皇后难题的类(class)。我添加了一个名为 populate 的测试方法,以确保我正确创建二维数组并正确动态分配内存,但是当调用此方法时程序崩溃,当我调试时弹出以下 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];

关于c++ - 二维数组在尝试填充时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43645404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com