变量''周围的堆栈已损坏

blu*_*ckk 7 c++

void GameBoard::enterShips()
{
    char location[1];
    int ships = 0;
    int count = 1;

    while(ships < NUM_SHIPS)
    {
        cout << "Enter a location for Ship " << count << ": ";
        cin >> location;
        cout << endl;

        Grid[location[0]][location[1]] = SHIP;
        ships++;
        count++;
    }
}
Run Code Online (Sandbox Code Playgroud)

我在写一个战舰游戏.我有电路板布局工作,计算机随机生成船只.现在我正在研究这种方法来提示用户输入船只的坐标当我运行程序时,它允许我输入5艘船.当我进入第6艘船时,它给了我这个错误.

变量位置周围的堆栈已损坏.

我在网上寻找答案,但没有找到任何独家的答案.

任何帮助,将不胜感激.

SLa*_*aks 12

location是一个单一的数组char.
没有location[1].


Tug*_*tes 6

您正在location向用户提示数组的内存地址.您应该分别询问位置索引:

void GameBoard::enterShips()
{
    int location[2];
    int ships = 0;
    int count = 1;

    while(ships < NUM_SHIPS)
    {
        cout << "Enter a location for Ship " << count << ": ";
        cin >> location[0];
        cin >> location[1];
        cout << endl;

        Grid[location[0]][location[1]] = SHIP;
        ships++;
        count++;
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,int location[2];因为大小为1的数组只能容纳一个元素.我还将元素类型更改为int.从控制台读取字符将导致ASCII值,这可能不是您想要的.