程序已停止工作?如何使int数组大小超过1,000,000?

夢のの*_*のの夢 0 c++ sieve-of-eratosthenes

赋值:在eratosthenes筛上编写一个c ++程序,打印出1到1,000,000之间的所有素数.我已经意识到,当我有一个非常大的数字,如1,000,000,程序停止工作,对于9,000这样的小数字,该程序工作得非常好.有没有办法让1,000,000作为整数数组大小?

#include <iostream>

using namespace std;

void sieve(int [], int num);

int main()
{
    int numOfElements;
    cout<<"please input number"<<endl;
    cin>>numOfElements;
    int primeArray[numOfElements];
    sieve(primeArray, numOfElements);
    return 0;
}

//prime number: any whole number greater than one and has factors of only the number itself and one.
void sieve(int prime[], int num){
    int i,j;
    for(int a=0;a<num;a++){
        prime[a]=a+1;
    }
    prime[0]=0;//we know 1 is not a prime;
    for(i=2;i<=num;i++){
        if(prime[i-1]!=0){
            cout<<i<<endl;
        }
        for(j=i*i;j<=num;j+=i){
            prime[j-1]=0;
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

Bat*_*eba 5

能够编写int primeArray[numOfElements];(这称为可变长度数组)是编译器扩展:不是标准C++的一部分.我希望你的编译器警告你这件事; 如果没有,请确保正确设置警告级别.

但在这种情况下,这是一个有争议的问题:尝试在堆栈上分配如此大的数组将失败.堆栈大小限制为一兆字节的大小.

最好的补救方法是使用a std::vector(i)是标准C++,(ii)将在堆上分配内存.

如果必须使用数组,则可以使用int* primeArray = new int[numOfElements].不要忘记释放内存delete[],注意括号.