How do I create an array in C++ which is on the heap instead of the stack? How do I create an array in C++ which is on the heap instead of the stack? arrays arrays

How do I create an array in C++ which is on the heap instead of the stack?


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;


The more C++ way of doing it is to use vector. Then you don't have to worry about deleting the memory when you are done; vector will do it for you.

#include <vector>std::vector<int> v(262144);


new allocates on the heap.

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