Dynamic Arrays in System Verilog

Welcome to the System Verilog tutorial series! If you have any doubts / suggestions, please let us know!  Dear visitor, please Sign up / Login for Free and get privileged access! You can copy code, download free tutorials and do more when you’re logged in!

Verilog does not allow changing the dimensions of the array once it is declared. Most of the time in verification, we need arrays whose size varies based on the some behavior. For example Ethernet packet varies length from one packet to other packet. In verilog, for creating Ethernet packet, array with Maximum packet size is declared and only the number of elements which are require for small packets are used and unused elements are waste of memory.

To overcome this deficiency, System Verilog provides Dynamic Array. A dynamic array is unpacked array whose size can be set or changed at runtime unlike verilog which needs size at compile time. Dynamic arrays allocate storage for elements at run time along with the option of changing the size.

Declaration Of Dynmic Array:

integer dyna_arr_1[],dyn_arr_2[],multi_dime_dyn_arr[][];

Allocating Elements:

New[]:The built-in function new allocates the storage and initializes the newly allocated array elements either to their default initial value.
dyna_arr_1 = new[10] ;// Allocating 10 elements
multi_dime_dyn_arr = new[4];// subarrays remain unsized and uninitialized

Initializing Dynamic Arrays:

The size argument need not match the size of the initialization array. When the initialization array<92>s size is greater, it is truncated to match the size argument; when it is smaller, the initialized array is padded with default values to attain the specified size.
dyna_arr_2 = new[4]('{4,5,6}); // elements are {4,5,6,0}

Resizing Dynamic Arrays:
Using new[] constructor and its argument, we can increase the array size without losing the data content.
Dyna_arr_1 = new[100] (dyna_arr_1); // Previous 10 data preserved

Copying Elements:

Copy constructor of dynamic arrays is an easy and faster way of creating duplicate copies of data.
Dyna_arr_2 = new[100](dyna_arr_1);// allocating and copying 100 elements.
Dyna_arr_1 = [1000]; // Previous data lost. 1000 elements are allocated.

1-8

RESULT:
4
8
0

The information about the size of the dynamic array is with the array itself. It can be obtained using .size() method. This will be very helpful when you are playing with array. You don’t need to pass the size information explicitly. We can also use system task $size() method instead of .size() method. SystemVerilog also provides delete() method clears all the elements yielding an empty array (zero size).