Why am i getting segmentation error for this problem in coding blocks ide alone?

#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
int a[n+1]={0};
int l[n+1]={0};
int r[n+1]={0};
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
l[0] = a[0];
r[n - 1] = a[n - 1];

for (int i = 1; i < n; i++)
{
    l[i] = max(l[i - 1], a[i]);
}

for (int i = n - 2; i >= 0; i--)
{
    r[i] = max(r[i + 1], a[i]);
}
int water = 0;
for (int i = 0; i < n; i++)
{
    water += (min(l[i], r[i]) - a[i]);
}
cout << water;

}

Hey @kani001
Give custom input with it,otherwise it may assume any garbage value which can be greater than 10^6 and try to create array of that size which gives segmentation error :slight_smile:

when i declare the arrays in int main() the program gives error,but when i declare it globally it works…what is the reason behind it?

The maximum size arrays u can create inside a function is close to 10^6 and outside is close to 10^8

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.