kravemir
kravemir

Reputation: 10986

Where are dynamic size arrays created on? (stack or heap)

For example, I have an array with dynamic size based on user input:

int n;
cin >> n;
int items[n];

Is this array allocated on stack? Or is it on heap like if I have written:

int n, *items;
cin >> n;
items = new int[n];
...
delete [] items;

Edit: I understand what the second code does. I'm asking whether the first code does the same thing like the second, but with less amount of lines.

Upvotes: 3

Views: 3386

Answers (3)

csteifel
csteifel

Reputation: 2934

Your first block of code will fail to compile, you cannot allocate a dynamically sized array without the use of a memory allocation with either new or malloc/calloc/realloc.

In order to do what you want you will need to do what you have in the second block, which will be allocated on the heap always.

Dynamic = Heap. Non-dynamic = Stack.

Always remember to free your memory!

Upvotes: -1

Richard J. Ross III
Richard J. Ross III

Reputation: 55553

Your first example isn't using a dynamic array at all - it's using a stack-allocated variable length array (which usually behind the scenes is equivalent to an alloca call, with the exception of the sizeof operator), which is a feature of C99, not C++.

Your second array, of course, is allocated on the heap via new.

Upvotes: 7

nabroyan
nabroyan

Reputation: 3275

You use new for allocating memory, so your array is stored in heap

Upvotes: 3

Related Questions