Static arrays are allocated on the stack and the size of the array must be known at compile time; that's why constants are the only acceptable parameter when creating an array like:
Dynamic arrays are allocated on the heap and the size of the array can be deferred to compile time. The
new
operator can allocate and return the address of a memory block in real-time and assign it to a suitable pointer. So statements like the following, do just that:
1 2 3
|
int size;
std::cin >> size;
int* myArray = new int[size];
|
The fact that your program compiled at all, with code like:
1 2 3
|
int size;
std::cin >> size;
int myArray[size];
|
is an anomaly to me, because it directly violates the syntax for static arrays, as the parameter
size
needs to be known at compile time for the stack to allocate enough space for the array. It probably works because the compiler is optimizing it to its dynamic counter-part.
You can't write
int* a
because that only allocates enough memory for a pointer-to-an-int, but NOT enough memory for an array of integers of an unknown size.
You may want to study up on Static Vs. Dynamic Arrays; Not to be dismissive, but there are hundreds of articles which probably explain this a lot better than me :)