Classic problem 1RE runs abnormally---defines memory-consuming arrays as member variables

Sometimes we will find that the array occupies too much memory, and the stack space that the function can use will not be enough to provide such a huge content, stack overflow occurs, and the program terminates abnormally.

In the future, for any situation that needs to open up a lot of memory space, we must define it outside the function, that is, define it as a global variable.
#include <stdio.h>
#include<iostream>
#define MAX 1000000
#define dis 500000
using namespace std;

int a[MAX+1];//Must be defined as a member variable
int main(){
   int n,m,b;
   int cnt=0;

   while(scanf("%d %d",&n,&m)!=EOF){

    for(int i=0;i<=MAX;i++){
        a[i]=0;
    }
    for(int i=0;i<n;i++){
        cin>>b;
        a[b+dis]=1;
    }
    for(int i=MAX;i>=0;i--){
        if(a[i]==1){
            cnt++;
            cout<<i-dis<<" ";
        }
        if(cnt==m)
            break;
    }

   }



return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325678136&siteId=291194637