Fun with SystemVerilog Dynamic Arrays

Did you know you can have multi-dimensional dynamic arrays in SystemVerilog? It's sometimes hard work, but you can, eg:

int array2d4 [][];

One way to initialise this is to just call new with an assignment pattern as its argument, eg:

array2d4 = new[3]('{'{0,1,2,3},'{4,5},'{6}});

If you don't do this, then calling new is hard work: you have to call it for the outer dimension and then loop round the inner dimensions calling it separately for each element. (I'll perhaps go into more detail in a future post - watch this space.)

Notice also that a multi-dimensional dynamic array doesn't have to be rectangular. In the above example, each row has a different length. (Or column. Who cares?)

A customer asked me what foreach did with a dynamic array that wasn't rectangular. It turns out that it copes admirably. Good old SystemVerilog.

foreach(array2d4[i,j])
  $display("array2d4[%0d][%0d]= %d", i, j, array2d4[i][j]);


Another customer asked me what happened if you delete a dynamic array that has already been deleted:

array2d4.delete;
array2d4.delete;


The answer turns out to be: nothing. Typical SystemVerilog:

module array;
  initial begin
    int k, array2d4 [][];
    array2d4 = new[3]('{'{0,1,2,3},'{4,5},'{6}});
    $display("array2d4= %p", array2d4);
    foreach(array2d4[i,j])
      $display("array2d4[%0d][%0d]= %d", i, j, array2d4[i][j]);
    array2d4.delete;
    array2d4.delete;
  end         
endmodule


https://www.edaplayground.com/x/3xST

Also there are more examples on EDA Playground at:

https://www.edaplayground.com/x/2urb (the same as the one linked to above)
https://www.edaplayground.com/x/3Scz
https://www.edaplayground.com/x/6Cuu

A customer asked me about this. I didn't know the answer, so I wrote a few lines of code on EDA Playground. EDA Playground is great for that, because it's always on. You don't have to queue for licences, wait for EDA tools to start, create new files, fire up editors...

Comments

Popular posts from this blog

Bit Width Casting in SystemVerilog

How to convert a std_logic_vector to a hex string?

Can you add/remove more than 1 item from a queue?