0

What is the difference between the below two statements?

i) long long int ar[n+1];

ii) long long int *ar=new long long int[n+1]();

For the array manipulation question in hackerrank, my code failed a few test cases when I used the first statement, but got correct answer with the second statement.

int main()
{
    long long int n,m,a,b,k,i,x=0,maxi=INT_MIN;
    cin>>n>>m;
    //long long int ar[n+1];
    long long int *ar=new long long int[n+1]();
    while(m--) {
        cin>>a>>b>>k;
        ar[a]+=k;
        if((b+1)<=(n))
        ar[b+1]-=k;
    }
    for(i=1;i<=n;i++) {
       x=x+ar[i];
       if(maxi<x) 
       maxi=x;
    }
    cout<<maxi;
    return 0;
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • Difference: first is ill-formed, second is well-formed (but not recommended). – L. F. Oct 05 '19 at 07:01
  • Your first attempt does not initialise the array elements, causing undefined behaviour when you later use their indeterminate values. – molbdnilo Oct 05 '19 at 08:21

1 Answers1

0

i) long long int ar[n+1];

This is valid only when n is known at compile time, which is not in your case. It may compile because of an extension some compilers have.

If n was known at compile time and you had a valid code ar will be allocated in automatic memory.

ii) long long int *ar=new long long int[n+1];

ar here will be allocated in dynamic memory there is almost no limit on n and you have to take care of its life yourself.

Every new should come with a delete

Oblivion
  • 7,176
  • 2
  • 14
  • 33