What is the difference between:
int myArray[5];
and
int* myArray = new int[5];
What is the difference between:
int myArray[5];
and
int* myArray = new int[5];
int myArray[5]
is a bunch of five integers with automatic (or static) storage duration (local memory, often classified as "in stack"). Local memory gets cleared in C++ when the specific scope is exited.
int* myArray = new int[5]
is a bunch of five integers on with dynamic storage duration (dynamic memory, often classified as "in heap"). Dynamic memory won't get cleared when the specific scope is exited (myArray
has to be an int pointer to store the location of your dynamically created memory).
View the following example:
void foo(){
int myArray[5];
}
void bar(){
int* myArray_dynamic = new int[5];
}
int main(){
foo();
bar();
}
foo
will use stack memory, so when foo
returns/exits the memory will get freed automatically. However, the dynamic allocated memory, which location is stored in myArray_dynamic
in bar
won't get freed, as the compiler will only free the memory of myArray_dynamic
, not the memory that's stored at its value.
This will create a memory leak, so for every use of new
or new[]
there has to be a call of delete
or delete[]
(except you are working with smart pointers, but that's for another question).
The correct version of bar
is
void bar(){
int* myArray_dynamic = new int[5];
delete[] myArray_dynamic;
}
The primary reason to pick one or the other is that dynamic allocation is slower, but can be any size (automatic arrays must have a fixed compile-time size), and also that space on the stack is limited, and if you run out, very bad things happen.
The first is an array that's a block of memory allocated either statically or as an automatic variable on the stack during the execution of a function ... it really depends on the context in which its declared/defined.
The second won't compile :-)
To be serious, you really want:
int* myArray = new int[5];
which means we've declared a pointer-type variable that points to an array of integers, and the array of integers is allocated dynamically by the C++ runtime on the heap by the call to new
, which is a segment of memory allocated by the OS for your process to dynamically allocate variables in.
The difference is the lifetime.
int myArray[5];
This reserves storage for an array 5 of int
. If myArray
is declared at block scope, the array is discarded at the end of the block where it is declared.
int* myArray = new int[5];
This dynamically allocates an array 5 of int
, the array exists until it is freed with delete []
.
What is the difference
One is valid.
The other is not.
In the second you must write
int* myArray = new int[5];
new
retuns pointer to the area dynamically allocated in heap.