2

我正在尝试编写一个在 C++ 中生成 500 万个不同随机数的程序。下面是代码:

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int main() {
    unsigned before = clock();
    srand(time(NULL));
    long numbers[5000000];
    for (int i = 0; i < 5000000; i++)
        numbers[i] = rand() % 5000000;
    for (int i = 0; i < 5; i++)
        cout<<numbers[i]<<endl;
    cout<<clock() - before<<endl;
    return 0;
}

每次我运行它时,什么都没有发生,程序在我身上崩溃了。我似乎找不到我做错了什么,因为代码是如此简单。有人可以帮帮我吗?谢谢你。

4

2 回答 2

4
long numbers[5000000];

will try to allocate 5 million * sizeof(long) bytes of stack. This will almost certainly overflow.

You could move the variable to have static duration instead

static long numbers[5000000];

or you could allocate it dynamically

long* numbers = new long[5000000];
// calculations as before
delete [] long;
于 2013-10-11T23:18:19.410 回答
2

You're allocating 20 MiB of data on the stack, but your system isn't configured to allow that.

  1. You don't need to save any of them if you're just printing them.
  2. You can make the variable static.
  3. You can dynamically allocate the array.

Any of those should work.

于 2013-10-11T23:19:24.573 回答