我正在使用C ++编写我自己的扫雷游戏(我最熟悉的语言),当我在二维数组中存储一个常量时,它有时最终会存储一个随机值。
这是我的代码:
using namespace std;
Table::Table() {
tiles[16][16] = {0};
covers[16][16] ={1};
}//stores position of mines, covers, and values
//places mines on the board
void Table::placemines() {
int minecount=0;
int i = rand()%15;
int j = rand()%15;
while(minecount<40){
if (tiles[i][j] == 0) {
tiles[i][j] = -10;
minecount++;
} else {}
i = rand()%15;
j = rand()%15;
}
}
和我的main.cpp显示值
using namespace std;
int main() {
Table newtable = Table();
newtable.placemines(6, 7);
for (int j = 0; j < 16; j++) {
for (int i = 0; i < 16; i++) {
cout << newtable.tiles[i][j] << ' ';
}
cout << '\n';
}
}
和输出
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 -10 -10 -10 0 0 1 -10 0 0
0 0 0 0 0 0 0 -10 0 -10 -10 0 -10 0 0 0
0 0 0 0 0 -10 0 0 0 -10 -10 0 -10 0 0 0
-10 0 0 -10 -10 0 0 -10 -10 0 0 0 0 -10 0 0
-10 0 -10 0 0 -10 0 0 0 0 0 0 0 -10 0 0
0 0 0 0 0 0 0 0 -10 -10 0 1920169263 0 -10 0 0
0 0 -10 0 0 0 0 0 0 -10 -10 1651076143 0 0 0 0
0 0 0 0 0 0 0 0 -10 -10 0 1819894831 -10 0 0 0
0 0 0 0 0 0 0 0 0 0 0 100 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 -10 0 0 0 0
0 0 0 0 0 0 0 -10 0 -10 0 32 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
-10 0 0 -10 0 0 0 0 0 0 -10 2 0 0 0 0
-10 0 0 0 0 -10 0 0 0 -10 0 4 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 0
有人能说出发生了什么吗?谢谢!
答案 0 :(得分:1)
缺少太多代码,没有声明,没有placemines()
代码
你有错误:
tiles[16][16] = {0};
此语句将索引为16和16的数组的某些元素设置为0.如果您的数组定义为type tiles[16][16]
,则表示您写入深渊并导致UB(因为数组的最后一个元素是{{1 }})。
如果必须初始化数组,请使用tiles[15][15]
http://en.cppreference.com/w/cpp/algorithm/fill。对于零初始化,这有效:
std::fill
另一个可能的错误:
Table::Table() : tiles{0} {
您必须使用数组的大小才能正确覆盖范围。
PS。在全球范围内避免int i = rand()%15;
,pleeeese。