Lably
Skip to content

Dynamic array

List data structure to which elements can be added/removed

  • 8 min read
  • 6 chapters

Related on Lably

Through Computer science, Array (data type) and Geometric progression

A dynamic array is not the same thing as a dynamically allocated array or variable-length array, either of which is an array whose size is fixed when the array is allocated, although a dynamic array may use such a fixed-size array as a back end.

Bounded-size dynamic arrays and capacity

A simple dynamic array can be constructed by allocating an array of fixed-size, typically larger than the number of elements immediately required. The elements of the dynamic array are stored contiguously at the start of the underlying array, and the remaining positions towards the end of the underlying array are reserved. Elements can be added at the end of a dynamic array in constant time by using the reserved space until this space is completely consumed.

When all space is consumed and an additional element is to be added, the underlying fixed-size array needs to be increased in size. Typically, resizing is expensive because it involves allocating a new underlying array and possibly copying each element from the original array.

Elements can be removed from the end of a dynamic array in constant time, as no resizing is required. The number of elements used by the dynamic array contents is its logical size or length, while the size of the underlying array is called the dynamic array's physical size or capacity. The capacity is the maximum possible size without relocating data.

A fixed-size array will suffice in applications where the maximum logical size is fixed (e.g. by specification), or can be calculated before the array is allocated. A dynamic array might be preferred if:

  • the maximum logical size is unknown, or difficult to calculate, before the array is allocated
  • it is considered that a maximum logical size given by a specification is likely to change
  • the amortized cost of resizing a dynamic array does not significantly affect performance or responsiveness

Sign in to keep reading

5 more chapters are free with a Lably account.

More in Computing and communication