Nick Bolton
Nick Bolton

Reputation: 39560

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

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];

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);

Should I just go with malloc?

Upvotes: 31

Views: 98204

Answers (7)

Reed Copsey
Reed Copsey

Reputation: 564441

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;

Upvotes: 77

Wilka
Wilka

Reputation: 29603

Your syntax for using new was wrong, it should be:

int *myArray = new int[262144];

you only need to put the size on the right of the assignment.

However, if you're using C++ you might want to look at using std::vector (which you will have) or something like boost::scoped_array to make the the memory management a bit easier.

Upvotes: 2

Brian Neal
Brian Neal

Reputation: 32389

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);

Upvotes: 28

John MacIntyre
John MacIntyre

Reputation: 13031

I believe

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

should be

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

or better yet

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

Upvotes: 1

Tommy Hui
Tommy Hui

Reputation: 1336

The reason the first try didn't work is that the syntax is incorrect. Try this:

int *myArray = new int[SIZE];

Upvotes: 2

Mitch Wheat
Mitch Wheat

Reputation: 300579

new allocates on the heap.

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

Upvotes: 3

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507045

As the number is not necessarily known at compile time, the type is a pointer:

int *myArray = new int[262144];

Upvotes: 1

Related Questions