1

https://www.hackerrank.com/challenges/variable-sized-arrays/problem

This is the problem statement. I tried the following code

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    int n,q;
    cin>>n>>q;
    int n1;
    int A[n][1000000];
   
for(int i =0; i<n; i++)   
{ cin>>n1;
     
    for(int j=0; j<n1; j++){
        int c;
        cin>>c;
        A[i][j] = c;
    }
}

int a,b;
for(int i=0;i<q; i++){
cin>>a>>b;
    
    cout<<A[a][b]<<"\n";
}
    return 0;
}

This code passes the sample test case and other custom inputs(I have tried for small number of input values). But it does not work for Test cases in which the value of n and q (as mentioned in the problem) are large. It gives the "Segmented Fault" error. Can someone please explain why I am getting that error.

  • You're getting a (nomen omen) stack overflow. This array is too big to fit in stack memory, so the program crashes. – Yksisarvinen Apr 08 '21 at 11:28
  • [VLA's are _not_ part of the C++ standard](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) and you discovered one of the reason why you shouldn't use them. You can use `std::vector` instead. – Lukas-T Apr 08 '21 at 11:29
  • 1
    Btw, in the last line before "Input format", the question itself links you to the correct way of creating a variable length array. It's called [`std::vector`](https://en.cppreference.com/w/cpp/container/vector) – Yksisarvinen Apr 08 '21 at 11:31

1 Answers1

0

Over here int A[n][1000000]; your allocating a n * 1000000 number of elements. That is a huge number. If we consider an int to be 32 bits (or 4 bytes), your talking about n * 4000000 bytes worth of data, which will most probably will be in the range of Megabytes and hence your error. This is easily too much to be stack allocated, and greatly inefficient.
Consider using std::vector<> instead.

D-RAJ
  • 3,263
  • 2
  • 6
  • 24