intArray不断崩溃。访问冲突错误

时间:2016-02-10 13:34:04

标签: c++

出于某种原因,我的intArray因为访问冲突错误而在多个阶段一直崩溃,有人能发现问题吗?

int main()
{
   int height = 10, width = 10; //Size of the grid
   Mine mineClass;
   Grid gridClass;
   cout << "------------" << endl << "Welcome to Minesweeper." << endl << "------------" << endl << "Created by Joel Draper, 2015." << endl << "------------" << endl;
   char* grid = new char[height*width];
   gridClass.startGrid(height, width, grid); //Initialises the grid with a default value 
   mineClass.randomMine(height, width); //Initialises the grid with random mines 
   gridClass.drawGrid(height, width, grid); //Allows the user to view the grid
   while (isRunning)
   {
      mainOutput(height, width, gridClass, grid); //Prevents main function   from being filled up with output text 
      //cout << "------------" << endl;
   }
   endGame(); 
   delete[] grid;
   return 0;
}

初始化网格

void Grid::startGrid(int height, int width, char grid[])
{
    intArray = new int[height*width];
    for (int h = 0; h < height; h++)
    {
        for (int w = 0; w < width; w++)
        {
            intArray[h*w] = 0;
            grid[h*w] = '*';
        }
    }
}

填充网格函数(在集合函数中调用,这就是问题所在)

void Grid::fillGrid(int mRow, int mColumn, int width)
{
    cout << intArray;

    cout << mRow << " " << mColumn << endl;

    if (intArray[width * mRow + mColumn] == 0)
    {
        intArray[width * mRow + mColumn] = 2;
        cout << "mine placed" << endl;
    }
}

1 个答案:

答案 0 :(得分:0)

初始化intArray时,请使用

intArray = new int[height*width];

heightwidth10。这将为您提供一个大小为100且有效索引为[0, 99]的数组。

然后在fillGrid()中,正如您在评论中所说的mRowmColumn[1, 10]范围内的一些随机数。所以当你这样做时

intArray[width * mRow + mColumn] 

您有(10 * [1,10]) + [1,10]作为计算或索引。如果mRow == 10,则我们(100) + [1,10]超出intArray的有效索引范围。这是未定义的行为,并且应该是访问违规的原因,因为您正在访问不属于该阵列的内存。

如果您将mRowmColumn的范围更改为[0, 9],则(10 * [0, 9]) + [0, 9]中的最大值可能会99落入有效范围内intArray

的索引范围