是否可以将1000万个数字存储在数组中? [英] Is it possible to store 10 million numbers in array?

查看:402
本文介绍了是否可以将1000万个数字存储在数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道数组中可以存储多少个数字?

I want to know how many numbers can you store in array?

srand (time(NULL));
int array[10000000];
for(int i = 0; i < 10000000; i++){
    array[i] = (rand() % 10000000) + 1;
}

每次我要在数组中存储1000万个数字时,我的程序崩溃了(Eclipse).我什至尝试过Visual Studio,它崩溃了.

Every time I want to store 10.000.000 numbers in array my program crashed (Eclipse). I even tryed Visual Studio and it crashed to.

所以我想知道我可以在数组中存储多少个数字,或者我的代码有问题吗?

So i want to know how many numbers can I store in array or is something wrong with my code?

推荐答案

您可以存储尽可能多的数字,但是不能那样做.程序崩溃的原因是您使用的是自动"变量,该变量分配在堆栈"上.堆栈的大小通常比堆"要多得多,因此使用如此大的自动变量可能会导致...等待...

You can store as many numbers as you have memory for, but you cannot do it like that. The reason your program crashes is that you are using an "automatic" variable, which is allocated on the "stack." The stack is much more limited in size than the "heap" typically, so using automatic variables of such large size may result in a...wait for it...

堆满!

相反,请尝试以下操作:

Instead, try this:

int* array = new int[10000000];

然后使用它:

delete[] array;

第二步将学习智能指针;在这种情况下,您可以使用boost::scoped_array之类的东西,但是根据喜欢的库(或者如果您具有C ++ 11),有很多选择.

Step two will be to learn about smart pointers; you can use something like boost::scoped_array for this case, but there are lots of options depending on which libraries you prefer (or if you have C++11).

如果您使用的是C ++ 11,则可以使用"RAII"来避免记住何时何地调用delete.只需执行以下操作即可分配数组:

If you have C++11 you can use "RAII" to avoid needing to remember when and where to call delete. Just do this to allocate the array:

std::unique_ptr<int[]> array(new int[10000000]);

或者只使用一个向量,该向量总是动态分配其内容(松散地说是在堆上"):

Or just use a vector, which always allocates its contents dynamically ("on the heap", loosely speaking):

std::vector<int> array(10000000); // 10000000 elements, all zero

这篇关于是否可以将1000万个数字存储在数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆