-3

I am running this code on online compiler:

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

I get a segmentation error. Can someone help me with this problem?

After reading numberOfMoves the code is stopped to execute, I believe. But I do not know for sure.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • 3
    `string direction[numberOfMoves]` This is not legal C++, see for example [Variable Length Array (VLA) in C++ compilers](https://stackoverflow.com/questions/39334435/variable-length-array-vla-in-c-compilers) why. – dxiv Dec 02 '20 at 07:16

2 Answers2

3

Changing from an illegal variable-length-array to a C++ std::vector container is so highly likely to fix all your segmentation fault problems that I won't go into details.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
0

You can not do it according to cpp standards.

string direction[numberOfMoves] = {"right", "up", "left", "down", "right"};

But if you are forced to do so, Do it via run time memory allocation something like this

string *direction = new string[numberOfMoves];
Umar Farooq
  • 418
  • 2
  • 14