5

What are the advantages of using dynamic memory allocation to create an array compared to the ordinary allocation of elements in an array?

1
  • On some platforms, dynamic memory area is much larger than local (or automatic) storage. In common terms, the heap may allow larger storage than the stack or application local storage. Commented Feb 22, 2010 at 18:33

7 Answers 7

9

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

3

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.

Comments

2

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

0

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

0

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.

Comments

0

In nutshell, it helps programmer to create Array of size which user says.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.