cout中断错误

时间:2018-05-12 11:22:52

标签: c++ visual-studio

我正在写一个简单的生命游戏模拟器。一切顺利,除非在最后,当结果由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

1 个答案:

答案 0 :(得分:1)

问题是cellTable声明:

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

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

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