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

2022-01-22 00:00:00 arrays malloc stack c++ heap-memory

我有一个非常大的数组,它的长度必须是 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;

相关文章