簡體   English   中英

中斷錯誤

[英]Break error on cout

我正在寫一個簡單的《人生游戲》模擬器。 除非最后,一切正常,但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;

}

斷點截圖:

點擊查看截圖

問題是cellTable聲明:

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

全局變量使用0隱式初始化,因此cellNumber將指向大小為0的數組,並且任何訪問cellTable項的嘗試都將導致未定義的行為。

最好將所有變量都設置為局部變量,然后將其顯式傳遞給函數。 而不是手動分配數組,您應該使用std::vector ,或者至少在為cellNumber分配適當的數字后(在獲取xy值之后)分配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM