Tutorials

Learn More

Dynamic Array in SystemVerilog

As name dynamic suggests, an array whose size can be changed during run time simulation.

The size of an array can be specified during run-time by using new[ ]. 

Note: By default, the size of a dynamic array is 0 unless a new[ ] is used.

Dynamic array declaration

bit [2:0] array []; 
string str_arr [];

// To allocate the size of an array
array = new[2];

Dynamic array Methods

Methods

Description

function int size()

Returns the current size of a dynamic array

function void delete()

Delete array results in an empty dynamic array i.e. zero-sized array.

new[ ]

To create a memory. It can also be used to resize or copy a dynamic array.

Note: The new [ ] is different from the function new() which is used in the OOP concept. [Read more in SystemVerilog Classes].

Dynamic array Example

module dynamic_array_example;
  int array [];
  initial begin
    array = new[5];
    array = '{5, 10, 15, 20, 25};
    
    // Print elements of an array
    foreach (array[i]) $display("array[%0d] = %0d", i, array[i]);
    
    // size of an array
    $display("size of array = %0d", array.size());
    
    // Resizing of an array and copy old array content
    array = new[8] (array);
    $display("size of array after resizing = %0d", array.size());
    
    // Print elements of an array
    foreach (array[i]) $display("array[%0d] = %0d", i, array[i]);
    
    // Override existing array: Previous array elememt values will be lost
    array = new[6];
    $display("size of array after overriding = %0d", array.size());
    
    // Print elements of an array
    foreach (array[i]) $display("array[%0d] = %0d", i, array[i]);
    
    array.delete();
    $display("size of array after deleting = %0d", array.size());
    
  end
endmodule

Output:

array[0] = 5
array[1] = 10
array[2] = 15
array[3] = 20
array[4] = 25
size of array = 5
size of array after resizing = 8
array[0] = 5
array[1] = 10
array[2] = 15
array[3] = 20
array[4] = 25
array[5] = 0
array[6] = 0
array[7] = 0
size of array after overriding = 6
array[0] = 0
array[1] = 0
array[2] = 0
array[3] = 0
array[4] = 0
array[5] = 0
size of array after deleting = 0

System Verilog Tutorials