数组导致程序崩溃c ++

时间:2016-05-04 00:15:01

标签: c++ arrays

所以我在为课堂写作的程序中遇到了一个问题。在尝试更改数组元素的值时,我会看到一个窗口,显示“程序已停止工作”。

此代码崩溃了我的程序:

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;
}
}

1 个答案:

答案 0 :(得分:2)

您要在每个循环中将spaces添加到turtleYturtleX

我建议你将语句移到for循环之外:

case SOUTH:
    for (int i = 0; i < spaces; i++) {
        if (penDown)
            board[turtleY + i][turtleX] = 1;
    }
    turtleY += spaces;
    break;

另外,如果您还没有这样做,则需要在向所有方向调整turtleYturtleX之前进行边界检查。