It's mostly a scope thing.
That creates a
local array that is automatically destroyed when it goes out of scope.
This creates an array on the heap that has a lifetime for as long as you need it (it is never automatically destroyed... it is only destroyed when you delete[] it).
Also... the standard does not allow you create a local array with a variable size. The size has to be known at compile time. However, for heap arrays, you can have a variable size. So:
1 2 3 4
|
int size = getSomeValueFromUser();
int* foo = new int[size]; // Ok
int bar[size]; // Not ok (though some compilers may allow it anyway... others might error)
|
Use the local array when you just need a small array for use in a function... or if you need a reasonably small, fixed-size array.
Use the 'new' version... well... never. Manual memory management in C++ should be avoided. There are usually better alternatives.
Better alternatives would be a vector:
1 2 3 4 5
|
int size = 22;
std::vector<int> foo(size);
foo[0] = 1;
foo[1] = 4;
// etc
|
Or a unique_ptr (C++11):
1 2 3 4 5
|
int size = 22;
std::unique_ptr<int[]> foo(new int[size]);
foo[0] = 1;
foo[1] = 4;
// etc
|
Both have the advantage of automatically cleaning up. Vector also has the advantage of being resizable (so if you need the array to grow or shrink, just call .resize() with a new size and vector will add/remove elements to the end to accommodate the new size).