显示正确的值后,数组生成不正确的值

时间:2014-10-19 18:12:56

标签: c++ arrays pointers

此代码是minMax函数的一大段代码的一部分,用于生成井字游戏的所有可能的游戏状态,它将根据获胜或失败所需的回合次数计算得分并选择最大的得分转弯,然后转移到那个位置。

我的问题是根据棋盘上的空缺点创建新游戏状态。

我创建了一个动态二维数组,它保存了新的可能状态数,以及它将用于扫描输赢的新游戏状态,或者递归回minMax以重复该过程。

for( int i=0; i<3; i++)
{
    for ( int j=0; j<3; j++)
    {
        if(gBoard[i][j] == 0)
        {
            turnCount++;    //getting number of possible new game states to create

        }
    }
}

int** newState = new int*[turnCount]; //creates pointer array that for number of possible newStates

for(int i=0; i<9; i++)
{
    newState[i] = new int[i];
}

然后我接受newState [] []数组并使用下面的代码用上面的新游戏状态填充它。

//Creating new game states based on all new possible moves



for( int i=0; i<3; i++)
{
    for ( int j=0; j<3; j++)
    {
        count=0;
        if(gBoard[i][j] == 0)
        {
            for( int x=0; x<3; x++)
            {
                for( int y=0; y<3; y++)
                {
                    newState[nState][count] = gBoard[x][y];
                    //newState[nState][tick] = player; //first empty place filled with "player" peice

                    //cout<<newState[nState][count];
                    count++;

                }
            }

            cout<<endl;
            for(int i=0; i<9; i++)
            {
                cout<<newState[nState][i]; //Filled correctly with the current game state
                //With nState 6 starting from 0
            }
            cout<<endl;
            cout<<"nState: "<<nState;
            cout<<endl;
            nState++;
        }
        tick++;
    }
}

现在不是我没有用他们各自的举动填补新游戏状态,因为我试图找出我当前的问题。

创建新nState时上面的代码在运行时在终端中产生以下结果,

100000001
nState: 0

100000001
nState: 1

100000001
nState: 2

100000001
nState: 3

100000001
nState: 4

100000001
nState: 5

100000001
nState: 6

如您所见,newState [nState] []生成了正确的nStates数,并使用gameBoard值填充了那些nStates。

然而,在我这样做之后再次调用newState [] [],我在第四个空格中得到一个随机的1值。显示nState [nState] [i]的代码如下。

nState = 0;
cout<<endl;
for(int i=0; i<9; i++)
{
    cout<<newState[nState][i]; //nState at 0, same as first iteration from the top of the start of the main and it doesn't work. i is reset, I'm getting the iterations for one nState that is in the array and the value of nState [i], yet it's producing giberish.

}
cout<<endl<<"nState: "<<nState<<endl;

当代码运行时,终端为newState [nState] [i];

吐出这个
100010001
nState: 0

我完全难过了。我认为代码中没有任何错误会突然产生不同的结果。我测试过以确保在所有循环发生时nState保持正确,并且正如您所看到的那样。如果有人有任何想法,我会喜欢这里,因为我相信我的功能逻辑对其他一切都是正确的,但这在代码中产生了一个主要障碍。

1 个答案:

答案 0 :(得分:0)

修复了,摆脱了newState数组的动态分配,刚刚创建了一个静态数组,可以容纳9个newStates,即该板的最大newStates数。

相关问题