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;
}
2
  • Difference: first is ill-formed, second is well-formed (but not recommended). Commented Oct 5, 2019 at 7:01
  • Your first attempt does not initialise the array elements, causing undefined behaviour when you later use their indeterminate values. Commented Oct 5, 2019 at 8:21

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.