我在学java之后正在学习c++,并编写了一个程序来用dfs解决某个游戏。问题是运行时,有时程序不执行并给出 0xC0000005 错误,但有时运行顺利,但用随机值填充状态数组。我认为它与 c++ 内存分配有关,我搞砸了,因为我不知道我在做什么
这是代码(假设数据被声明为某个包含 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;
}
堆栈上的局部变量必须显式初始化。尝试一下
in data[7][7] = {0};
这会将所有 49 个元素初始化为 0。