Why did I write the declaration into the main function that the program does not run

67 Views Asked by At

When I write the following three lines of code into the main function, the program will not run.

const int N = 500005;
long long a[N]={0};
long long b[N]={0};

At first, I thought it was a problem with "const", but I deleted "const" and it still couldn't run. When I put these three lines of code outside the main function and the program can run successfully, I don't know why. Here is the complete code:

using namespace std;
int main()
{
  const int N = 500005; 
  long long a[N]={0};
  long long b[N]={0};
  long long n,q;
  cin>>n>>q;
  for(long long i=1;i<=n;i++)
  {
    cin>>a[i];
    b[i]=a[i]-a[i-1];
  }
  while(q--)
  {
    long long l,r,x;
    cin>>l>>r>>x;
    b[l]+=x;
    b[r+1]-=x;
  }
  for(long long i=1;i<=n;i++)
  {
    b[i]+=b[i-1];
    if(b[i]<0)
    {
        cout<<"0"<<" ";
    }
    else
        cout<<b[i]<<" ";
  }

  return 0;
}
1

There are 1 best solutions below

0
On

Within main the arrays have automatic storage duration. Declared in the namespace scope the arrays have static storage duration that is reserved before the program will be run.

So the reason of the problem is that there is no enough memory used for automatic variable allocations for such big arrays.

Instead of the arrays you could use objects of the standard container std::vector<long long>.