所以我在为课堂写作的程序中遇到了一个问题。在尝试更改数组元素的值时,我会看到一个窗口,显示“程序已停止工作”。
此代码崩溃了我的程序:
case EAST:
cout << "test";
for (int i = 0; i < spaces; i++) {
if (penDown)
board[turtleY][turtleX + i] = 1; //this is the line causing the crash
turtleX += spaces;
}
break;
turtleX和turtleY通过引用传递给此函数。
void moveForward(int spaces, bool penDown, int &turtleX, int &turtleY, int currentDirection, int board[][NUM_COLS]) {
switch (currentDirection) {
case NORTH:
for (int i = 0; i > spaces; i--) {
if (penDown)
board[turtleY + i][turtleX] = 1;
turtleY -= spaces;
}
break;
case EAST:
cout << "test";
for (int i = 0; i < spaces; i++) {
if (penDown)
board[turtleY][turtleX + i] = 1;
turtleX += spaces;
}
break;
case SOUTH:
for (int i = 0; i < spaces; i++) {
if (penDown)
board[turtleY + i][turtleX] = 1;
turtleY += spaces;
}
break;
case WEST:
break;
}
}
答案 0 :(得分:2)
您要在每个循环中将spaces
添加到turtleY
和turtleX
。
我建议你将语句移到for
循环之外:
case SOUTH:
for (int i = 0; i < spaces; i++) {
if (penDown)
board[turtleY + i][turtleX] = 1;
}
turtleY += spaces;
break;
另外,如果您还没有这样做,则需要在向所有方向调整turtleY
或turtleX
之前进行边界检查。