子数组核心转储问题


int proximity = 0;
for(int i = coord.x - 1; i <= coord.x + 1; i++)
{
    if(i < 0)
    {
        i = coord.x; //prevents from leaving the top of sub array
    }
    for(int j = coord.y - 1; j <= coord.y + 1; j++)
        {
            if(j < 0)
            {
                j = coord.y; 
            }
            if((board[i][j] == bomb) || (board[i][j]==hidden))
                proximity++;
        } //nested for loop runs through a sub array based on user input between 0-4

}

我正在尝试在子数组中检查坐标,我尝试了许多不同的变体,但是我无法在第4行中输入坐标,而不会得到核心转储错误。我知道这可能是我需要打字的一条简单的小线来解决此问题,但我很困惑。

在您的代码中您执行了下边界检查,但是丢失了上限检查。您需要确保X或Y坐标都不会超过板边界。

假设您的x_size ans y_size是各个尺寸的尺寸

,请在循环中添加额外的条件
for(int i = coord.x?coord.x  - 1:0; 
    i <= coord.x + 1 && i < X_SIZE; 
    i++)
{
    for(int j = coord.y?coord.y - 1:0; 
        j <= coord.y + 1 && j < Y_SIZE; 
        j++)
    {
          if((board[i][j] == bomb) || (board[i][j]==hidden))
          {
              proximity++;
          }
    }
}

最新更新