提问人:Aryan Yoshi Joshi 提问时间:9/17/2023 更新时间:9/17/2023 访问量:36
C++代码有时会因错误0xC0000005退出,有时会执行,但会用随机整数填充数组
C++ code sometimes exits with 0xC0000005 error and sometimes executes, but fills array with random integers
问:
我在 java 之后学习 c++,并编写了一个程序来使用 dfs 解决某个游戏。问题是在运行时,有时程序不执行并给出0xC0000005错误,但有时运行平稳,但用随机值填充状态数组。我认为它与我搞砸的 c++ 内存分配有关,因为 idk 我在做什么
下面是代码(假设数据被声明到某个包含 0、1、2 和 3 的数组):
#include <iostream>
using namespace std;
#include <stack>
void printArray(int arr[][7])
{
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 7; j++)
cout << arr[i][j] << ", ";
cout << '\n';
}
cout << '\n';
}
bool solution (int arr[][7])
{
for (int i = 0; i < 7; i++)
for(int j = 0; j < 7; j++)
if (arr[i][j] == 0)
return false;
return true;
}
int main()
{
int data[7][7];
printArray(data);
stack<int(*)[7][7]> nodes;//stack of each possible gamestate
nodes.push(&data);
while (nodes.size() > 0)
{
int (*statePtr)[7][7] = nodes.top();//accessing top element as pointer
nodes.pop();
int state[7][7];
for (int i = 0; i < 7; i++)//passing into 2d array by value
for (int j = 0; j < 7; j++)
state [i][j] = (*statePtr[i][j]);
if (solution(state))
{
printArray(state);
break;
}
for (int i = 0; i < 7; i++)//for all empty values in state
for (int j = 0; j < 7; j++)
if (state[i][j] == 0)
{
bool existNeigh1, existNeigh2, existNeigh3;
existNeigh2 = false;
existNeigh3 = false;
int neighbors[8][2] = {
{1, 0}, {1, 1}, {0, 1}, {-1, 1},
{-1, 0}, {-1, -1}, {0, -1}, {1, -1}};
for (int n = 0; n < 8; n++)//checking if this cell has a 1, 3, 5 neighbor
{
if (i+neighbors[n][0] >= 0 && i+neighbors[n][0] < 7 && j+neighbors[n][1] >= 0 && j+neighbors[n][1] < 7)
{
int neighborValue = state[i+neighbors[n][0]][j+neighbors[n][1]];
if (neighborValue == 1)
existNeigh1 = true;
if (neighborValue == 2)
existNeigh2 = true;
if (neighborValue == 3)
existNeigh3 = true;
}
}
if (existNeigh1)//if so, adding an updated board to the stack
{
int stateCopy[7][7];
for(int r = 0; r < 7; r++)
for(int c = 0; c < 7; c++)
stateCopy[r][c] = state[r][c];
stateCopy[i][j] = 1;
nodes.push(&stateCopy);
//printArray(stateCopy);
}
if (existNeigh2)
{
int stateCopy[7][7];
for(int r = 0; r < 7; r++)
for(int c = 0; c < 7; c++)
stateCopy[r][c] = state[r][c];
stateCopy[i][j] = 2;
nodes.push(&stateCopy);
//printArray(stateCopy);
}
if (existNeigh3)
{
int stateCopy[7][7];
for(int r = 0; r < 7; r++)
for(int c = 0; c < 7; c++)
stateCopy[r][c] = state[r][c];
stateCopy[i][j] = 3;
nodes.push(&stateCopy);
//printArray(stateCopy);
}
}
}
return 0;
}
答:
0赞
B. Pantalone
9/17/2023
#1
必须显式初始化堆栈上的局部变量。尝试
in data[7][7] = {0};
这会将所有 49 个元素初始化为 0。
评论
2赞
Tim Roberts
9/17/2023
没错,但无关紧要。这不是这里的缺陷。
评论
nodes.push(&stateCopy);
- 当超出范围时,此指针几乎会立即悬空。然后访问它是未定义的行为。你想要 ,并在其他地方使用而不是常规数组。这些可以用单个(没有循环)复制。stateCopy
std::stack<std::array<std::array<int, 7>, 7>>
std::array<std::array<int, 7>, 7>
=
stateCopy
std::stack