【问题标题】:Break error on coutcout 中断错误
【发布时间】:2018-05-12 11:22:52
【问题描述】:

我正在编写一个简单的 Game Of Life 模拟器。一切都很顺利,除了最后,当 cout 打印结果时,我得到一个中断错误。我不明白为什么,我想寻求您的帮助。

变量

#include <iostream>
using namespace std;

struct cell
{
    bool isAlive;
    int posX;
    int posY;
    int numberOfAliveNeighbours;
    char group;
};
int cellNumber;
cell *cellTable = new cell[cellNumber];
int numberOfTunrs;

主要:

int main()
{
        int x;
        int y;
        int cellCounter = 0;
        cin >> x >> y;
        cellNumber = x*y;
        cin >> numberOfTunrs;
        for (int i = 0; i < x; i++)
        {
            for (int j = 0; j < y; j++)
            {
                char cellAliveChar;
                cin >> cellAliveChar;
                if (cellAliveChar == '#')
                {
                    cellTable[cellCounter].isAlive = true;

                }
                else if (cellAliveChar == '.')
                {
                    cellTable[cellCounter].isAlive = false;

                }
                cellTable[cellCounter].numberOfAliveNeighbours = 0;
                cellTable[cellCounter].group = '#';
                cellTable[cellCounter].posX = j;
                cellTable[cellCounter].posY = i;
                cellCounter++;

            }
        }

        doTurns(x, y);
        int result;
        result = countGroups();
        **cout << result << endl;**
        //here is breakpoint 
        cin >> x;


}

countGroups(如果相关,idk):

int countGroups()
{
    int max = 0;
    int current;
    int i = 0;
    char checkingGroup = 'A';
    do
    {
        current = 0;
        for (int j = 0; j < cellNumber; j++)
        {
            if (cellTable[j].group == checkingGroup + i)
            {
                current++;
            }
        }
        i++;
        if (current > max)
        {
            max = current;
        }
    } while (current != 0);

    return max;

}

断点截图:

Click to view the screenshot

【问题讨论】:

  • **cout &lt;&lt; result &lt;&lt; endl;** 为什么?,如果你已经做了 using namespace std 或 std::cout &lt;&lt; result &lt;&lt; std::endl; ,你的意思是 cout &lt;&lt; result &lt;&lt; endl;
  • } while (current = 0); 应该是 } while (0 == current); 或一些适当的条件。也不清楚cellTable 是什么以及doTurns 内部发生了什么很可能是某种缓冲区溢出破坏程序状态。
  • @VTT 您好,我添加了全局变量并对其进行了编辑。断点仍然出现:(
  • @xanadev 是的,我只是想标记断点出现在代码中的位置 :) 我编辑了我的帖子并添加了变量和包含,我正在使用命名空间 std,您可能想要检查

标签: c++ visual-studio


【解决方案1】:

问题是cellTable声明:

int cellNumber;
cell *cellTable = new cell[cellNumber];

全局变量被隐式初始化为 0,因此 cellNumber 将指向 0 大小的数组,任何访问 cellTable 项的尝试都会导致未定义的行为。

最好将所有变量设为局部变量并将它们显式传递给函数。您应该使用std::vector,而不是手动分配数组,或者至少在为cellNumber 分配适当的数字后进行分配(在获得xy 值之后)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多