Reputation: 10986
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
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
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
Reputation: 3275
You use new
for allocating memory, so your array is stored in heap
Upvotes: 3