如何在 C++ 中创建一个位于堆而不是堆栈的数组?

How do I create an array in C++ which is on the heap instead of the stack?(如何在 C++ 中创建一个位于堆而不是堆栈的数组?)
本文介绍了如何在 C++ 中创建一个位于堆而不是堆栈的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常大的数组,它的长度必须是 262144 个元素(将来可能会更大).我试过像这样在堆栈上分配数组:

I have a very large array which must be 262144 elements in length (and potentially much larger in future). I have tried allocating the array on the stack like so:

#define SIZE 262144
int myArray[SIZE];

但是,当我尝试添加超过某个点的元素时,当我尝试访问它们时,这些值似乎有所不同.我知道这是因为堆栈上只有有限数量的内存,而不是具有更多内存的堆.

However, it appears that when I try and add elements past a certain point, the values are different when I try to access them. I understand that this is because there is only a finite amount of memory on the stack, as opposed to the heap which has more memory.

我尝试了以下方法,但运气不佳(无法编译):

I have tried the following without much luck (does not compile):

#define SIZE 262144
int *myArray[SIZE] = new int[SIZE];

然后我考虑使用 malloc,但我想知道是否有更类似于 C++ 的方式来执行此操作...

And then I considered using malloc, but I was wondering if there was a more C++ like way of doing this...

#define SIZE 262144
int *myArray = (int*)malloc(sizeof(int) * SIZE);

我应该只使用 malloc 吗?

推荐答案

你会想像这样使用 new:

You'll want to use new like such:

int *myArray = new int[SIZE];

我还会提到另一面,以防万一......

I'll also mention the other side of this, just in case....

自从您从堆栈过渡到堆后,您还需要在完成后清理此内存.在堆栈上,内存会自动清理,但在堆上,你需要删除它,因为它是一个数组,你应该使用:

Since your transitioning from the stack to the heap, you'll also need to clean this memory up when you're done with it. On the stack, the memory will automatically cleanup, but on the heap, you'll need to delete it, and since its an array, you should use:

delete [] myArray;

这篇关于如何在 C++ 中创建一个位于堆而不是堆栈的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

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

相关文档推荐

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?(易失性成员变量与易失性对象?)