What are the advantages of using dynamic memory allocation to create an array compared to the ordinary allocation of elements in an array?
7 Answers
int x[100]; is fixed size and you can not expand it. Its lifetime is tied to the context where it was created and can not be passed around different functions/methods.
int *x = new int[n]; ... delete[] x; can be reallocated so it can resize and n does not have to be known in the compile time (so you can ask user how many numbers do she need and create an array of that size). As pointed by @Neil Butterworth, this is creating array on the heap and can be larger in size, while the static variant is creating array on the stack.
std::vector wraps a lot of this magic reallocation code and probably this is something you should use in your code.
Comments
The basic advantages of a dynamically allocated array are that you can determine the size of a dynamically allocated array at run-time, and, because the array is on the heap rather than the stack, it can be larger than a static array. It is important to remember though, that std::vector does this work for you. The occasions on which you should roll your own array class are few and far between. Use std::vector,
Comments
When you are allocating arrays then size of the array has to be given at the compile time. In that case most of the times, either you are allocating more memory or less memory.
This is where dynamic memory allocation helps you out so that you can actually allocate only those chunks of memory that are really needed and as and when you are done with the memory management you can free the memory.