我正在用 C++ 实现埃拉托色尼筛法算法,但遇到了问题。当我将我的数组初始化为一个非常大的值(例如 100 万)时,它会中断,因为我将太大的数组分配给堆栈。 C 中的答案是像这样使用 malloc Sieve of Eratosthenes ,但这个解决方案在 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;
}
最佳答案
在堆栈上分配这么大的数组会导致 stack overflow .要在堆上分配它,您可以这样做:
int *integerList = new int[1000000];
或者更好的是,使用 std::vector
代替。
关于c++ - 堆数组分配而不是在堆栈上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22801061/