到达线路时程序崩溃

Program crashes when reaching a line

本文关键字:程序 崩溃 线路      更新时间:2023-10-16

程序到达player[aplyr].grid[X][Y] = isSHIP;时崩溃

const char isSHIP = 'S';
struct PLAYER{
char grid[10][10];
}player[3]; //player 1 and 2. Ignore player 0

int main ()
{
    int X;
    int Y;
    //"PLACE SHIPS" phase of game
    //Loop through each player... 
    for (int aplyr=1; aplyr<3; ++aplyr)
    {
        //Loop through each ship type to place
        for (int thisShip=0; thisShip<15; ++thisShip)
        {       
         //Get input from user
            PlaceShips();
         //Add the FIRST grid point to the current player's game board
            player[aplyr].grid[X][Y] = isSHIP;
        }

            //Loop back until 15 points have been placed
    }
        //Loop back through each player
}
void PlaceShips()
{
    int x, y, player;
    bool goodInput = false;
    do {
         //get X pick
        cout << "Enter X and Y coordinates:  ";
        cin >> x >> y;
        if (x >= 10 && y>=10)
        {
            goodInput = false;
            cin.clear();
            cout << "Out of Range!";
            break;
        }
        else
        {
            goodInput = true;
        }
    } while (!goodInput);  
}

在 main 函数中,您正在创建变量 X 和 Y,而无需初始化它们的值。这意味着它们可以包含任何值,并且很可能超出网格范围。这将导致程序在指定行崩溃。