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

本文标题为:如何在 C++ 中创建一个位于堆而不是堆栈的数组

基础教程推荐