创建具有300万个元素的双数组 [英] Creating a double array with 3 million elements
问题描述
我正在尝试创建一个包含300万个随机元素的双精度数组:
I am trying to create an array of doubles with 3 million random elements:
#include <iostream>
#include <cstdlib>
#include <random>
#include <ctime>
using namespace std;
int main(int argc, const char * argv[]) {
// generating random numbers
mt19937 rng_engine(0); // seed = 0
uniform_real_distribution<double> dist2(0,10);
clock_t begin = clock();
// create a random 2d array 1 million x 3
double coords[1000000][3];
for (int i=0; i<1000000; i++) {
for (int j= 0; j<3; j++) {
coords[i][j] = dist2(rng_engine);
//cout << "i = " << i << ", j = " << j << ", val = " << coords[i][j] << endl;
}
}
clock_t end = clock();
double elapsed = double(end - begin) / CLOCKS_PER_SEC;
cout << "elapsed: " << elapsed << endl;
return 0;
}
当我尝试在Xcode中运行此代码时,我得到 EXC_BAD_ACCESS(代码= 2,地址= 0x7fff5e51bf9c)
.我试图编译它并在命令行中运行它,这给了 Segmentation错误:11
.当我将数组大小更改为 [100000] [3]
时,使元素数达到300,000,代码开始运行.我不明白的是为什么拥有300万双打是一个问题.数组大小不是24 MB吗?(8个字节* 3,000,000 = 24 MB)我缺少什么?
When I try to run this in Xcode, I get EXC_BAD_ACCESS (code=2, address=0x7fff5e51bf9c)
. I tried to compile it and run it in the command line, which gave Segmentation fault: 11
. When I change the array size to [100000][3]
, making the number of elements 300,000, the code runs. What I don't understand is why is it a problem to have 3 million doubles. Wouldn't the array size be 24 MB? (8 bytes * 3,000,000 = 24 MB) What am I missing?
推荐答案
您几乎肯定会溢出堆栈.
You're almost certainly overflowing the stack.
避免这种情况的明显选择是使数组 static
(当它位于 main
中时实际上并没有太大变化,但是通常以不同的方式分配它)或(通常更好)改为使用 std :: vector
.
Obvious choices to avoid that would be to make the array static
(doesn't really change much when it's in main
, but typically allocates it differently) or (usually better) use an std::vector
instead.
这篇关于创建具有300万个元素的双数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!