Dynamic Arrays might seem simple at first glance, but their inner workings will open your eyes ๐.
But first of all, let's start with the basics.
What are Dynamic Arrays ?
Dynamic Arrays are resizable arrays that can automatically adjust their size when elements are added โ or removed โ.
Unlike Static Arrays which has a fixed size that is determined during compile time, the size of Dynamic Arrays can be adjusted during run time as per the need.
But are Dynamic Arrays really Dynamic ?
Actually Dynamic Arrays are built on top of Static Arrays. Surprising right ? Let's dive deeper ๐คฟ
The Working Mechanism โ๏ธ
Suppose we have a Dynamic Array myArr[3] = {2, 4, 6}
which is already full.
Now, If you want to add a new element to the array according to Dynamic Array, you may think that a new slot will be added to the existing array and the element is then after inserted into it. What if I tell you "YOU ARE WRONG" ? ๐คจ
The Moment of Truth โ
What actually happens is that a new array is created with double or greater capacity than the existing array ( no worries, will explain the reason for this too ) , and all of the existing elements are shifted to the new array, as well as new elements, and then the pointer head ๐ซต is shifted from the previous array to the new array ๐ซต, and the previous array is deallocated if necessary.
Now why the new array has double or much greater capacity than the previous array ? ๐คจ
It's simple.
So that we don't run out of space frequently, which would require us to create a new array every time we add a single new element, increasing the time complexity of the process. Instead, why not just create a little larger but not too large new array to balance the time and space complexity ?
So yeah that was it ๐คท
Now you know how Dynamic Arrays actually work. Understanding the mechanics of dynamic arrays is crucial for efficient programming.
As you continue your coding journey, keep these principles in mind to optimize your data handling strategies. Happy Coding!
Top comments (0)