A dynamic array is one dimension of an unpacked array whose size can be set or changed at runtime. The space for a dynamic array doesn’t exist until the array is explicitly created at runtime.
The syntax to declare a dynamic array is:
data_type array_name [];
where data_type is the data type of the array elements. Dynamic arrays support the same types as fixed-size arrays.
For example:
bit [3:0] nibble[]; // Dynamic array of 4-bit vectors
integer mem[]; // Dynamic array of integers
The new[] operator is used to set or change the size of the array.
The size() built-in method returns the current size of the array.
The delete() built-in method clears all the elements yielding an empty array (zero size).
The built-in function new allocates the storage and initializes the newly allocated array elements either to their default initial value or to the values provided by the optional argument.
The prototype of the new function is:
dynamic_array_name = new[expression][(expression)]
[ expression ]:
The number of elements in the array. Must be a non-negative integral expression.
( expression ):
Optional. An array with which to initialize the new array. If it is not specified, the elements of the newly allocated array are initialized to their default value. This array identifier must be a dynamic array of the same data type as the array on the left-hand side, but it need not have the same size. If the size of this array is less than the size of the new array, the extra elements shall be initialized to their default value. If the size of this array is greater than the size of the new array, the additional elements shall be ignored.
This argument is useful when growing or shrinking an existing array. In this situation, the value of ( expression ) is the same as the left-hand side, so the previous values of the array elements are preserved. For example:
integer addr[]; // Declare the dynamic array.
addr = new[100]; // Create a 100-element array.
...
// Double the array size, preserving previous values.
addr = new[200](addr);
The new operator follows the SystemVerilog precedence rules. Since both the square brackets [] and the parenthesis () have the same precedence, the arguments to this operator are evaluated left to right: [ expression ] first, and ( expression ) second.
The prototype for the size() method is:
function int size();
The size() method returns the current size of a dynamic array, or zero if the array has not been created.
int j = addr.size;
addr = new[ addr.size() * 4 ] (addr); // quadruple addr array
Note: The size method is equivalent to $length( addr, 1 ).
The prototype for the delete() method is:
function void delete();
The delete() method empties the array, resulting in a zero-sized array.
int ab [] = new[ N ]; // create a temporary array of size N
// use ab
ab.delete; // delete the array contents
$display( "%d", ab.size ); // prints 0