ch2-Dynamic Arrays

2019-10-24

SystemVerilog Dynamic Array

​ A dynamic array is an unpacked array whose size can be set or changed at run time, and hence is quite different from a static array where the size is pre-determined during declaration of the array. The default size of a dynamic array is zero until it is set by the new() constructor.

Syntax

A dynamic array dimensions are specified by the empty square brackets [ ].

1
2
3
4
5
[data_type] [identifier_name]  [];

bit [7:0] stack []; // A dynamic array of 8-bit vector
string names []; // A dynamic array that can contain strings

The new() function is used to allocate a size for the array and initialize its elements if required.

Dynamic Array Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
module tb;
// Create a dynamic array that can hold elements of type int
int array [];

initial begin
// Create a size for the dynamic array -> size here is 5
// so that it can hold 5 values
array = new [5];

// Initialize the array with five values
array = '{31, 67, 10, 4, 99};

// Loop through the array and print their values
foreach (array[i])
$display ("array[%0d] = %0d", i, array[i]);
end
endmodule

ynamic Array Methods

Function Description
function int size (); Returns the current size of the array, 0 if array has not been created
function void delete (); Empties the array resulting in a zero-sized array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
module tb;
// Create a dynamic array that can hold elements of type string
string fruits [];

initial begin
// Create a size for the dynamic array -> size here is 5
// so that it can hold 5 values
fruits = new [3];

// Initialize the array with five values
fruits = '{"apple", "orange", "mango"};

// Print size of the dynamic array
$display ("fruits.size() = %0d", fruits.size());

// Empty the dynamic array by deleting all items
fruits.delete();
$display ("fruits.size() = %0d", fruits.size());
end
endmodule

How to add new items to a dynamic array ?

​ Many times we may need to add new elements to an existing dyanmic array without losing its original contents. Since the new() operator is used to allocate a particular size for the array, we also have to copy the old array contents into the new one after creation.

1
2
3
4
5
6
int array [];
array = new [10];

// This creates one more slot in the array, while keeping old contents
array = new [array.size() + 1] (array);


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!