分段故障字符阵列

Segmentation Fault Character arrays

本文关键字:阵列 字符 故障 分段      更新时间:2023-10-16

我正试图从C++编程书中编写一个简单的TicTacToe游戏作为练习。这应该在不使用指针或向量的情况下完成,因为我只完成了数组一章。当我尝试运行代码时,遇到了分段错误。这是我的密码。。

#include <iostream>
#include <string>
#include <math.h>
using namespace std;
void displayArray( char array[3][3] );

main ()
{
    char board[][3] =
    {
        {' ',' ',' '},
        {' ',' ',' '},
        {' ',' ',' '}
    };

    int p1;
    int p2;
    int j2;
    int j1;
    int i2;
    int i1;
    for ( int i = 0; i < 9; i++)
    {
        if( pow(-1,i) == 1 )
        {
            while ( board[i1][j1] != ' ')
            {
                cout << "Player 1 insert your indicesn";
                cin >> p1 ;
                 i1 = floor(p1%10);
                 j1 = p1%10;
            }
            board[i1][j1] = 'X';
        }
        else
        {
            while ( board[i1][j1] != ' ')
            {
                cout << "Player 2 insert your indicesn";
                cin >> p2 ;
                  i2 = floor(p2%10);
                  j2 = p2%10;
            }
            board[i1][j1] = 'O';
         }
    }
    displayArray( board );
}

void displayArray( char array[3][3] )
{
    cout << "Board :n" ;
    for ( int i = 0; i < 3; i++ )
    {
        cout << array[i][0] << 't' << array[i][2] << 't' << array[i]   [2] << 'n';
    }
    cout << 'n' ;
}
   while ( board[i1][j1] != ' ')

CCD_ 1和CCD_。因此,当你做board[i1][j1]时,你可能正在触及未知的领域。这在c++中被称为Undefined behavior,如果您的代码这样做,运行时可以自由地做任何它想做的事情。在大多数情况下,这是一个细分故障。

还有这个部分:

while ( board[i1][j1] != ' ')
   {
        cout << "Player 2 insert your indicesn";
        cin >> p2 ;
        i2 = floor(p2%10);
        j2 = p2%10;
   }

是一个无限循环。你的意思是写i2j2吗?