检查2d数组中相邻单元时出错

error while checking adjacent cells in 2d array

本文关键字:单元 出错 2d 数组 检查      更新时间:2023-10-16

代码为棋盘上每个棋子B为黑,W为白,其中WB不能共用一条边。

的例子:

WBWB
BWBW
WBWB
BWBW
我的代码是:

#include <iostream> 
using namespace std;
int main()
{
    int n, m;
    cin >> n >> m;
    char chess[4][4];
    for (int i = 0;i<n;i++)
        for (int j = 0;j<m;j++)
            cin >> chess[i][j];
    for (int i = 0;i<n;i++)
        for (int j = 0;j<m;j++)
        {
            if (chess[i][j] == '.')
            {
                if (chess[i - 1][j] == 'W' || chess[i + 1][j] == 'W' || chess[i][j + 1] == 'W' || chess[i][j - 1] == 'W')
                    chess[i][j] = 'B';
                else
                    chess[i][j] = 'W';
            }
        }
    for (int i = 0;i<n;i++)
    {
        for (int j = 0;j<m;j++)
            cout << chess[i][j];
        cout << endl;
    }
    system("pause");
    return 0;
}
问题是当我运行这段代码时,输出是:
WBWB
BWBW
BBWB
WBBW

我调试了它,chess[2][-1]等于W,它超出了作用域,所以它应该是垃圾

您正在使用负数组索引。当ij为零时,

chess[i - 1][j]
// and
chess[i][j - 1]

chess[-1][j]
// and
chess[i][-1]

使用负数组索引是未定义的行为,任何事情都可能发生。您需要添加边界检查,以确保没有使用小于0或大于3的索引。您还需要检查chess[i + 1][j]chess[i][j + 1],因为当ij等于3时,您再次出界。