What is a Dynamic Array? #
A Dynamic Array is a one-dimensional unpacked array whose size can be set and changed during simulation runtime using the new[]
operator.
Unlike fixed arrays, dynamic arrays are ideal when the number of elements is not known in advance, such as in packet-based verification scenarios where the size can vary with each transaction.
Syntax:
data_type array_name[];
array_name = new[size]; // Allocates memory for given size
Example: Declaration and Initialization
module example;
int dyn_array[]; // Declare a dynamic array
dyn_array = new[5]; // Allocate 5 elements
foreach (dyn_array[i])
dyn_array[i] = i * 10; // Initialize values: 0, 10, 20, 30, 40
endmodule
Built-in Methods
Method | Description |
---|---|
.size() | Returns the number of elements |
.delete() | Frees memory and resets array to size 0 |
Resizing Dynamic Arrays
You can resize a dynamic array at runtime:
dyn_array = new[20]; // Resize with data loss
dyn_array = new[10](dyn_array); // Resize and keep old values
If you don’t use (old_array)
during resizing, previous values are discarded.
Deleting a Dynamic Array
dyn_array.delete(); // Clears all elements
After deletion:
- Array size becomes
0
- Memory is released
Example:
module test;
int dyn_array[];
initial begin
dyn_array = new[4]; // Allocate 4 elements
foreach (dyn_array[i])
dyn_array[i] = i + 1;
$display("Original size: %0d", dyn_array.size());
dyn_array = new[8](dyn_array); // Resize and keep old values
dyn_array[4] = 5;
dyn_array[5] = 6;
$display("Resized size: %0d", dyn_array.size());
dyn_array.delete(); // Free memory
$display("After delete: %0d", dyn_array.size());
end
endmodule
Output:
Original size: 4
Resized size: 8
After delete: 0
Comparison: Dynamic vs Fixed Arrays
Feature | Fixed Array | Dynamic Array |
---|---|---|
Size defined at | Compile time | Simulation time (runtime) |
Memory allocation | Static (stack) | Dynamic (heap) |
Resizable | ❌ No | ✅ Yes |
Dimensions allowed | 1D / Multi-D | Only 1D |
Out-of-bound access | Returns ‘x’ | Causes runtime error |
Supports methods | ❌ No | ✅ Yes (size() , delete() ) |