Why need dynamic array

In reply to hazhanken:
Yes, it’s true that a queue gives you all the same functionality as a dynamic array, as well as a fixed sized array. The difference is in the intended use of the array and how the simulator optimizes the data structure that represent the array.

A dynamic array is typically allocated with a size once, and then elements of the array are randomly accessed - similar to a fixed sized array. The elements are allocated contiguously in memory. It’s easy to calculate the address of each element by multiplying the element size by an index value to get an offset from the base address of the array. But if you want to change the size of the array, especially when you want to add more elements, the simulator needs to find an available larger contiguous space for the array and copy the existing elements to that space.

When using a queue, you typically access only the head or tail element, and are repeatedly adding and deleting one element at a time from the head or tail. A queue is implemented as a linked list, which makes head and tail access very simple. But this comes at the expense of taking up more memory for each element, and requires a traversal of elements to get to element in between the head an tail.

1 Like