动态数组类似C++中的new[]操作。可以在运行时指定数组大小。也可以删除以及重新分配动态数组。一旦动态数组被创建,将具有未打包的数组功能。动态数组必须在初始化之前先声明。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // declaration data_type array_name []; // allocation array_name = new [size_expression]; // allocation along with declaration data_type array_name = new [size_expression]; // declaration and initialization array_name = new [size_expression](initialization_array); // assignment array_name = another_array; |
支持如下操作:
new[]()
new[]函数将会为数组分配内存。此函数需要一个整数参数作为数组的大小,以及一个可选参数表示数组的类型。此可选参数可以是一个固定长度的数组,或者是另外一个动态数组,抑或是其他的容器类型(队列/列表),甚至是文字数组。如果此设置了参数,此参数用来对动态数组的元素进行初始化。
1 2 3 4 | int size = 4; logic [7:0] data[]; // array declaration data = new [size]({32, `bx, 0, `hBD}); data = new [2*size]; |
注意:用来指定数组大小参数的表达式不需要在编译时间是常数。可以对某个动态数组多次分配内存,之前分配的内存将会被垃圾回收器回收。
delete()
SystemVerilog为动态数组定义了delete()方法,此方法显式的收回动态数组的内存,类似C++中的delete[].
size()
size()方法返回值为数组长度的整数。对还没有被分配内存的动态数组以及被删除的数组,此函数返回'0'.
1 2 3 4 5 6 7 8 9 10 11 12 13 | module top; initial begin bit [3:0] foo [], bar[]; int count = 16; $ display (foo.size()); // displays 0; foo = new [count]; $ display (foo.size()); // displays 16; bar = new [20](foo); $ display (bar.size()); // displays 20; foo.delete(); $ display (foo.size()); // displays 0; end endmodule : top |
评论