Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 336
Nick Bolton Avatar asked Mar 24 '09 01:03

Nick Bolton


People also ask

How do I create an array in heap?

Creating an array in the heap allocates a new array of 25 ints and stores a pointer to the first one into variable A. double* B = new double[n]; allocates an array of 50 doubles. To allocate an array, use square brackets around the size.

Are arrays stored in stack or heap in C?

Arrays are stored the same no matter where they are. It doesn't matter if they are declared as local variables, global variables, or allocated dynamically off the heap.

Can array data be stored in heap?

Storage of Arrays As discussed, the reference types in Java are stored in heap area. Since arrays are reference types (we can create them using the new keyword) these are also stored in heap area.

Are arrays allocated on stack in C?

C language provides the alloca function to allocate arbitrary size array on the stack. After the function returns or the scope ends, the stack memory is automatically reclaimed back (popped back) without the developer having to deallocate it explicitly and thereafter is unsafe to access it again from another function.


2 Answers

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; 
like image 133
Reed Copsey Avatar answered Oct 20 '22 08:10

Reed Copsey


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); 
like image 32
Brian Neal Avatar answered Oct 20 '22 09:10

Brian Neal