变量''周围的堆栈已损坏 [英] Stack around the variable ' ' was corrupted

查看:167
本文介绍了变量''周围的堆栈已损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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++;
    }
}

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

Im writing a battleship game. I have the board layouts working and the computers randomly generated ships. Now I am working on this method to prompt the user to enter coordinates for the ships When I run the program, it allows me to enter 5 ships. When I enter the 6th ship, it gives me this error.

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

Stack around the variable location was corrupted.

我已经在网上寻找答案,却没有发现任何排他性的内容.

Ive looked for answers online and have not found anything exclusive.

任何帮助将不胜感激.

推荐答案

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

You are prompting the memory address of location array to your user. You should ask location indices separately:

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++;
    }
}

注意 int位置[2]; ,因为大小为1的数组只能容纳一个元素.我也将元素类型更改为int.从控制台读取char会产生ASCII值,这可能不是您想要的.

Notice int location[2]; since an array of size 1 can only hold one element. I also changed the element type to int. Reading char's from the console will result in ASCII values, which are probably not what you want.

这篇关于变量''周围的堆栈已损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆