在堆栈上声明大数组 [英] Declare large array on Stack

查看:33
本文介绍了在堆栈上声明大数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Dev C++ 编写一个模拟程序.为此,我需要声明一个数据类型为 double 的一维数组.它包含 4200000 元素 - 比如 double n[4200000].

I am using Dev C++ to write a simulation program. For it, I need to declare a single dimensional array with the data type double. It contains 4200000 elements - like double n[4200000].

编译器没有显示错误,但程序在执行时退出.我已经检查过,对于具有 5000 元素的数组,程序执行得很好.

The compiler shows no error, but the program exits on execution. I have checked, and the program executes just fine for an array having 5000 elements.

现在,我知道不建议在堆栈上声明如此大的数组.但是,问题是模拟需要我多次调用数组中的特定元素 - 例如,我可能需要 n[234]n[46664] 用于给定的计算.因此,我需要一个更容易筛选元素的数组.

Now, I know that declaring such a large array on the stack is not recommended. However, the thing is that the simulation requires me to call specific elements from the array multiple times - for example, I might need the value of n[234] or n[46664] for a given calculation. Therefore, I need an array in which it is easier to sift through elements.

有没有办法在堆栈上声明这个数组?

Is there a way I can declare this array on the stack?

推荐答案

不,没有(我们会说合理")方法在堆栈上声明这个数组.但是,您可以在堆栈上声明指针,并在堆上留出一些内存.

No there is no(we'll say "reasonable") way to declare this array on the stack. You can however declare the pointer on the stack, and set aside a bit of memory on the heap.

double *n = new double[4200000];

访问其中的 n[234],应该不会比访问您这样声明的数组的 n[234] 快:

accessing n[234] of this, should be no quicker than accessing n[234] of an array that you declared like this:

double n[500];

或者更好的是,你可以使用向量

Or even better, you could use vectors

std::vector<int> someElements(4200000);
someElements[234];//Is equally fast as our n[234] from other examples, if you optimize (-O3) and the difference on small programs is negligible if you don't(+5%)

如果你用 -O3 优化,它和数组一样快,而且更安全.与

Which if you optimize with -O3, is just as fast as an array, and much safer. As with the

double *n = new double[4200000]; 

除非这样做,否则您将泄漏内存的解决方案:

solution you will leak memory unless you do this:

delete[] n;

除了例外和各种各样的事情,这是一种非常不安全的做事方式.

And with exceptions and various things, this is a very unsafe way of doing things.

这篇关于在堆栈上声明大数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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