检查2d数组中相邻单元时出错
error while checking adjacent cells in 2d array
代码为棋盘上每个棋子B
为黑,W
为白,其中W
和B
不能共用一条边。
的例子:
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
,它超出了作用域,所以它应该是垃圾
您正在使用负数组索引。当i
或j
为零时,
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]
,因为当i
或j
等于3时,您再次出界。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 访问者访问变体并返回不同类型时出错
- 在Linux for Windows上编译C++代码时出错
- 读取文件的最后一行并输入到链接列表时出错
- 重载操作程序时出错>>用于类中的字符串 memebr
- 调用专用模板时出错"no matching function for call to [...]"
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 不同翻译单元中不可重载的非内联函数定义
- LINK 尝试使用 OpenSSL evp aes 256 c++ 时出错
- 在Google Kick start中提交时出错
- 在c++中访问int到类对象的映射时出错
- 分段错误当我试图运行程序时出错
- 使用dynamic_cast和构造函数时出错
- CHECK(调用)函数在Google Colab中出错
- 有什么好的方法可以让系统调用代理允许在单元测试中进行模拟
- 用pybind11包装C++抽象类时出错
- 在子目录中使用target_sources()命令时用于单元测试(qtest)的项目结构
- VC++本机单元测试,找不到调试符号
- 使用单元测试 (cppunit) 中另一个文件中定义的结构时出错
- 检查2d数组中相邻单元时出错