I'm initializing an array n-size with all zeros. Using the vector class or allocating with "new" works but with built-in array, i get segmentation fault in hackerrank c++.
long long arr[n];
for(int a = 0;a < n;a++) {
arr[n] = 0;
}
//segmentation fault in some cases.
long long arr = new long long[n]; // doesn't fail
vector<long long> arr(n,0); // works also
Complete code:
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
using namespace std;
typedef long long ll;
int main()
{
ll n,m;
ll biggest = 0;
ll current = 0;
cin >> n >> m;
ll arr[n];
for(int a = 0;a < n;a++) {
arr[a] = 0;
}
for(int i = 0;i < m;i++) {
ll a,b,k;
cin >> a >> b >> k;
arr[a - 1] += k;
if(b < n) arr[b] -= k;
}
for(int j = 0;j < n; j++) {
current += arr[j];
biggest = max(current,biggest);
}
cout << biggest << endl;
return 0;
}
Why built-in fails?