在 Stack 上声明大数组

2022-01-22 00:00:00 arrays memory stack c++ allocation

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

相关文章