简体   繁体   English

堆数组分配而不是堆栈

[英]Heap array allocation instead of on stack

I'm implementing the sieve of eratosthenes algorithm in C++, and I've run into a problem. 我正在用C ++实现eratosthenes算法的筛选,但遇到了一个问题。 When I initialize my array to a very large value, like 1 million, it breaks because I'm allocating too large of an array to the stack. 当我将数组初始化为非常大的值(例如1百万)时,它会中断,因为我向栈分配了太大的数组。 The answer in C would be to use malloc like this Sieve of Eratosthenes , but this solution does not work in C++ (to the best of my knowledge). 在C语言中,答案是使用像Eratosthenes筛子这样的 malloc,但是(据我所知)此解决方案在C ++中不起作用。 Any ideas on how I could get this program to work with very large numbers by allocating the array in the heap instead of the stack? 关于如何通过在堆中而不是栈中分配数组来使该程序以非常大的数量运行的任何想法? Thanks. 谢谢。

To see the problem I'm having, change the code below int integerList[1000], change 1000 to 1000000 or higher. 要查看我遇到的问题,请更改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;
}

Allocating an array of size that large on the stack leads to stack overflow . 在堆栈上分配大小较大的数组会导致堆栈溢出 To allocate it on the heap, you can do: 要在堆上分配它,您可以执行以下操作:

int *integerList = new int[1000000];

Or better, use a std::vector instead. 或更好,使用std::vector代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM