c++ - 堆数组分配而不是在堆栈上

标签 c++ arrays dynamic-allocation

我正在用 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/

相关文章:

c++ - list<string> 无法将其传递给 C++ 中的类

ios - 选择一个按钮后,如何取消选择阵列中的所有其他按钮?

C:尺寸大于 1000 的二维数组相乘会导致段错误

c - 尝试学习 C 中的动态内存分配

c - 链表初始化

c++ - 为什么输出显示为无符号数

c++ - 为什么我不能拥有带有此签名的 Q_PROPERTY?

javascript返回包含特定数组项的随机数据

c++ - STL <list> 搜索列表以查找项目属性

javascript - 如何在外部 Javascript 中使用 PHP 变量