在 Stack 上声明大数组

Declare large array on Stack(在 Stack 上声明大数组)
本文介绍了在 Stack 上声明大数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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.

这篇关于在 Stack 上声明大数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)