如何在C ++中创建一个在堆而不是堆栈上的数组? [英] How do I create an array in C++ which is on the heap instead of the stack?

查看:338
本文介绍了如何在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 ++中创建一个在堆而不是堆栈上的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆