How do I create an array in C++ which is on the heap instead of the stack?(如何在 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++ 中创建一个位于堆而不是堆栈的数组
基础教程推荐
- 设计字符串本地化的最佳方法 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01