0

The computer is giving segmentation fault whenever I try to read input into this. My input looks like:

7
1 2 3
2 3 1
1 4 4
4 6 7
7 5 2
3 5 1
4 5 5

Basically, I want to store the above input directly into a 2D array. The first column is X-coordinates, 2nd column Y-coordinate and finally the value needed to store in (X,Y) COORDINATE of a 2D array.

long leastTimeToInterview(int n, int k, int m) {
    int a[m+1][m+1];
    int i=0,x=0,y=0;

    for (i=1;i<=m;i++){
        scanf("%d %d",&x,&y);
        scanf("%d",&a[x][y]);
        a[y][x]=a[x][y];

    } 
    return 11; 
}
Joseph D.
  • 11,804
  • 3
  • 34
  • 67

2 Answers2

0

Like rustyx mentioned, this error could be a result of a stack overflow.

The easiest aproach would be to reduce the size of your array or use another data structure which allocates memory dynamically like std::vector, std::list or std::map.

In your example it also looks as if most of your array is empty. In this case i sugest using std::map. Some other optimisations in regard of memory usage are discussed in this question: Any optimization for random access on a very big array when the value in 95% of cases is either 0 or 1?

Detonar
  • 1,409
  • 6
  • 18
0

There is no such thing as dynamically sized array in C++'s type system so you need to change it to somthing else like std::vector. The other problem is that even if your compiler supports dynamically sized arrays you still get stack overflow (at least it's very likely). So I suggest that you change your function to something like this:

long leastTimeToInterview(int n, int k, int m) {
    std::vector<std::vector<int>> a(m + 1, std::vector<int>(m + 1));
    int i = 0, x = 0, y = 0;

    for(i = 1; i <= m; i++) {
        scanf("%d %d", &x, &y);
        scanf("%d", &a[x][y]);
        a[y][x] = a[x][y];
    }
    return 11;
}

There still might be an error in the logic of your application but your example and explanation don't give enough information to tell that.

navyblue
  • 776
  • 4
  • 8