首页 > 解决方案 > 在线编译的代码抛出分段错误

问题描述

我在在线编译器上运行此代码:

#include <iostream>

using namespace std;

int main () {
    int x_coordinate = 0, y_coordinate = 0;
   
    int numberOfMoves;
    cin >> numberOfMoves;
    // cout << "i went here" << x_coordinate << numberOfMoves;

    string direction[numberOfMoves] = {"right", "up", "left", "down", "right"};
    int dir[numberOfMoves] = {0, 1, 2, 3, 0};
    for (int i = 1; i <= numberOfMoves; i++) {
        // cout << "i went here";
        int distance = (i%5)*10;
        int currentDirection = dir[i % 5];
        switch (currentDirection) {
            case 0: 
                x_coordinate += distance;
                break;
            case 1:
                y_coordinate += distance;
                break;
            case 2: 
                x_coordinate -= distance;
                break;
            case 3:
                y_coordinate -= distance;
                break;
            default:
                break;
        }
    }
    cout << x_coordinate << y_coordinate << "\n";
    return 0;
}

我得到一个segmentation error. 有人可以帮我解决这个问题吗?

看完numberOfMoves代码就停下来执行,我相信。但我不确定。

标签: c++

解决方案


从非法的可变长度数组更改为 C++std::vector容器非常有可能解决您所有的分段错误问题,我不会详细介绍。


推荐阅读