Dynamic Memory Allocation
What are the advantages of us开发者_运维知识库ing dynamic memory allocation to create an array compared to the ordinary allocation of elements in an array?
You don't have to know the size of the array in advance, or over-allocate memory to account for large arrays. This allows your program to be more efficient with its memory use.
Arrays created dynamically can typically be larger than those created automatically, and can have longer lifetimes. But both have numerous disadvantages compared to using a std::vector.
1) Dynamic memory allocation allows for lots of liberty when it comes to managing the lifecycle of an object.
2) The size of the array can also be controlled with more liberty.
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.
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,
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.
In nutshell, it helps programmer to create Array of size which user says.
精彩评论