Venus
Venus

Reputation: 167

Dynamic Memory Allocation

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

Upvotes: 5

Views: 3821

Answers (7)

Jennis Vaishnav
Jennis Vaishnav

Reputation: 341

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

Upvotes: 0

EnthuDeveloper
EnthuDeveloper

Reputation: 670

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.

Upvotes: 0

Liz Albin
Liz Albin

Reputation: 1499

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,

Upvotes: 0

Goran Rakic
Goran Rakic

Reputation: 1799

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.

Upvotes: 2

anon
anon

Reputation:

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.

Upvotes: 4

tvanfosson
tvanfosson

Reputation: 532695

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.

Upvotes: 9

jldupont
jldupont

Reputation: 96834

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.

Upvotes: 3

Related Questions