我遇到了问题 . 当我将我的数组初始化为一个非常大的值,如100万时,它会中断,因为我正在为堆栈分配太大的数组 . C中的答案是使用类似于Sieve of Eratosthenes的malloc,但是这个解决方案在C中不起作用(据我所知) . 关于如何通过在堆中而不是堆栈中分配数组来使这个程序能够处理非常大的数字的任何想法?谢谢 .
要查看我遇到的问题,请更改int integerList [1000]下面的代码,将1000更改为1000000或更高 .
int main(void)
{
int userInput = 0;
int integerList[1000] = {};
cout << "Please pick a number to find all prime numbers "
<< "from 2 to that number: " << endl;
//for the sake of writing out algorithm only, assume correct input
cin >> userInput;
//initialize array
for (int i = 2; i <= userInput; i++)
{
integerList[i] = i;
}
//implementation of the algorithm
for (int i = 2; i < userInput; i++)
{
if (integerList[i] != 0)
{
for (int j = 2; j < userInput; j++)
{
integerList[j*integerList[i]] = 0;
if (integerList[i] * j > userInput)
{
break;
}
}
}
}
for (int i = 0; i < userInput; i++)
{
if (integerList[i] != 0)
{
cout << integerList[i] << " ";
}
}
system("Pause");
return 0;
}
1 回答
在堆栈上分配大型数组会导致stack overflow . 要在堆上分配它,您可以执行以下操作:
或者更好的是,使用
std::vector
代替 .