Dynamic Array

Dynamic array is an unpacked array whose size can be set or changed at runtime.

The default size for dynamic array is zero until it set by the constructor new().

Declaration :

int dyn1_array[]; bit dyn2_array[];//Single dimensional dynamic array declaration

bit dyna_array[][];//Two dimensional dynamic array declaration

Memory Allocation :

dyn1_array = new [5]; // dynamic array with 5 index

dyn2_array = new [3]; // dynamic array with 3 index

Initialization :

dyn1_array = {1,2,3,4,5};

dyn2_array = {10,20};// Last index remain 0, since initialization not done

Dynamic array resize :

Using new[] constructor and its argument, we can increase the array size without losing the data content.

dyn1_array = new[10] (dyn1_array); // Previous 5 data preserved

The previous 5 elements are retained along with additional 5 index.So array gets resized without losing the previous content.

To check dyanic array size :

size( )    –> returns the current size of a dynamic array.

dyn1_array.size(); //Returns the current size

Dynamic Array deletion :

delete( ) –> It empties the array, resulting in a zero-sized array.

dyn1_array.delete(); // Delete the array

Why dynamic array ?

In static array, while declaration itself size need to be given.So in static array, we cannot able to change the size.

For example, If we declare a static array with 100 index, later we are using only 10 index in code, In this case memory get wasted. To avoid this dynamic array is most preferred one than static array.

Dynamic array is resizable by using new().