声明堆栈上的大阵 [英] Declare large array on Stack

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

问题描述

我使用的开发C ++写一个模拟程序。对于它,我需要声明一个数据类型为单维数组双击。它包含 420 元素 - 比如双N [420]

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天全站免登陆