Dynamic and Associative Arrays in SystemVerilog: A Complete Guide

In many verification environments, the size of the data to be handled is not always fixed. For example:

  • You may need to store an unknown number of transactions.
  • You might need to index data using keys instead of numerical indices.
  • You want arrays to grow or shrink dynamically based on the data being processed.

For these scenarios, dynamic arrays and associative arrays are much more flexible than static or fixed-size arrays.

  • Dynamic Arrays allow you to change the size of the array during runtime, making them suitable for handling collections of data whose size varies during simulation.
  • Associative Arrays enable you to access elements using keys (which can be of any data type) rather than just integer indices. This is useful when data is not organized sequentially or needs to be indexed by non-numeric values (e.g., strings).

Dynamic Arrays

A dynamic array in SystemVerilog is an array whose size can be changed at runtime. This type of array is particularly useful when the number of elements is not known ahead of time. Dynamic arrays are declared without specifying the size initially, and their size can be adjusted later using the new[] method.

Declaration of Dynamic Arrays

int array[];  // Declares a dynamic array of integers

Here, array[] is a dynamic array of integers. Initially, its size is undefined.

Allocating size to a dynamic array

To allocate or change the size of a dynamic array, you use the new[] method.

array = new[10];  // Allocates 10 elements to the dynamic array

After the new[] call, the dynamic array will have 10 elements, and you can access and assign values to them. The default value of these elements will be 0.

Example: Using Dynamic Arrays

module test;
  int array[];  // Declare a dynamic array

  initial begin
    array = new[5];  // Allocate 5 elements
    for (int i = 0; i < array.size(); i++) begin
      array[i] = i * 2;  // Assign values to the array
      $display("array[%0d] = %0d", i, array[i]);
    end

    array = new[10];  // Resize the array to hold 10 elements
    $display("New size of array: %0d", array.size());
  end
endmodule

Output:

array[0] = 0
array[1] = 2
array[2] = 4
array[3] = 6
array[4] = 8
New size of array: 10

Dynamic Array Methods

Dynamic arrays come with several useful methods:

  1. size(): Returns the current number of elements in the dynamic array.
int n = array.size();

2. new[]: Resizes the dynamic array to the specified size.

array = new[4];
array = new[10];          //increase the size by overriding the old values
array = new[10](array);   //increase the size by keeping the old values

3. delete(): Frees the memory allocated to the dynamic array and sets its size to 0.

array.delete();

Example: Deleting a dynamic array

module test;
  int array[];

  initial begin
    array = new[10];
    $display("Size before deletion: %0d", array.size());
    
    array.delete();  // Deletes the array, freeing its memory
    $display("Size after deletion: %0d", array.size());
  end
endmodule

Output:

Size before deletion: 10
Size after deletion: 0

When to Use Dynamic Arrays?

Dynamic arrays are perfect for situations where:

  • The number of elements is unknown at compile time.
  • You need the array to grow or shrink dynamically during simulation.
  • Memory efficiency is crucial, as dynamic arrays can be resized to use only the amount of memory necessary.

Associative Arrays

An associative array is an array that allows you to index elements using keys, which can be any data type (not just integers). Associative arrays are highly flexible and useful when the data is sparse or when it makes more sense to index elements using non-numerical values, such as strings or enums.

Declaration of Associative Arrays

int array[string];  // Declares an associative array indexed by strings

Here, array is an associative array where the key is a string, and the values are int. You can also use other types like int, enum, or bit as keys.

Example: Associative array Indexed by strings

module test;
  int scores[string];  // Associative array with string keys

  initial begin
    scores["Alice"] = 90;
    scores["Bob"] = 85;
    scores["Charlie"] = 92;

    $display("Alice's score: %0d", scores["Alice"]);
    $display("Bob's score: %0d", scores["Bob"]);
    $display("Charlie's score: %0d", scores["Charlie"]);
  end
endmodule

Output:

Alice's score: 90
Bob's score: 85
Charlie's score: 92

Associative Array Methods

SystemVerilog provides various methods for working with associative arrays:

  1. exists(): Checks if a specific key exists in the associative array.
if (scores.exists("Alice")) begin
  $display("Alice's score is present");
end

2. delete(): Removes an element from the associative array.

scores.delete("Bob");  // Deletes the entry with key "Bob"

3. num(): Returns the number of entries in the associative array.

int n = scores.num();

4. first() and last(): Returns the first and last key in the associative array, respectively.

string key;
if (scores.first(key)) begin
  $display("First key: %s", key);
end

5. next(): Returns the next key in the associative array after a given key.

string key;
if (scores.first(key)) begin
  do begin
    $display("Key: %s, Score: %0d", key, scores[key]);
  end while (scores.next(key));
end

Example: Associative array methods

module test;
  int scores[string];  // Associative array with string keys
  string key;

  initial begin
    // Add elements to the array
    scores["Alice"] = 90;
    scores["Bob"] = 85;

    // Check if a key exists
    if (scores.exists("Alice"))
      $display("Alice's score exists.");

    // Delete an element
    scores.delete("Bob");

    // Display number of elements
    $display("Number of entries: %0d", scores.num());

    // Iterate over the array
    if (scores.first(key)) begin
      do begin
        $display("Key: %s, Score: %0d", key, scores[key]);
      end while (scores.next(key));
    end
  end
endmodule

Output:

Alice's score exists.
Number of entries: 1
Key: Alice, Score: 90

When to Use Associative Arrays?

Associative arrays are ideal for situations where:

  • The index (key) is not an integer or the data is sparse.
  • You need to access elements by a non-sequential key (like a string, bit, or enum).
  • Memory efficiency is important for large datasets, as associative arrays use memory only for the elements that are added, not for unused indices

Key Differences Between Dynamic and Associative Arrays:

FeatureDynamic ArraysAssociative Arrays
Index TypeInteger indices (sequential)Any data type (string, enum, int, etc.)
SizeCan be changed dynamically using new[]Size is determined by the number of entries
MemoryMemory is allocated based on the array sizeMemory is allocated only for used entries
Best Use CaseWhen the array size changes dynamicallyWhen you need to index data with non-integer or sparse keys