What is an Associative Array? #
An Associative Array is a one-dimensional unpacked array in SystemVerilog where elements are indexed using non-consecutive values such as integers, strings, or even objects. Unlike fixed or dynamic arrays, storage is allocated only when an element is used, making associative arrays ideal for sparse data structures.
Syntax:
data_type array_name [index_type];
Example:
bit [31:0] mem[int]; // Integer-indexed associative array
string str_arr[string]; // String-indexed associative array
class C; // Class-based index
C obj;
bit [7:0] class_arr[C]; // Associative array indexed by class object
Differences from Regular Arrays
Feature | Fixed/Dynamic Arrays | Associative Arrays |
---|---|---|
Index Type | Integer (sequential) | Any scalar (int, string, class handle) |
Memory Allocation | Pre-allocated / on new | Allocated only on use |
Index Continuity | Contiguous | Non-contiguous (sparse) |
Element Order | Deterministic | Random / Implementation-defined |
Usage | Known size / dense memory | Unknown size / sparse memory |
Built-in Methods
SystemVerilog provides special methods for traversing and querying associative arrays.
Method | Description |
---|---|
.num() | Returns the number of entries |
.exists(idx) | Checks if an entry exists at the given index |
.first(idx) | Assigns the first index used to the variable idx |
.last(idx) | Assigns the last index used to the variable idx |
.next(idx) | Assigns the next index after idx to idx |
.prev(idx) | Assigns the previous index before idx to idx |
.delete() | Deletes all elements (or only the one at a given index) |
Example: Using Associative Array with Integer Index
module assoc;
bit [31:0] mem[*]; // Associative array with integer index
bit [31:0] i;
initial begin
// Store values at non-contiguous indices
mem[0] = 32'hFFAAFFAA;
mem[3] = 32'hFFAAFFAA;
mem[5] = 32'hFFAAFFAA;
mem[7] = 32'hFFAAFFAA;
$display("Size of array: %0d", mem.num());
// First index
mem.first(i);
$display("First index used: %0d", i);
// Next index
mem.next(i);
$display("Next index: %0d", i);
// Last index
mem.last(i);
$display("Last index used: %0d", i);
// Previous index
mem.prev(i);
$display("Previous index: %0d", i);
// Delete all elements
mem.delete();
$display("Size after delete: %0d", mem.num());
// Check existence
$display("Element exists? %0d", mem.exists(i));
end
endmodule
Output:
Size of array: 4
First index used: 0
Next index: 3
Last index used: 7
Previous index: 5
Size after delete: 0
Element exists? 0
Summary
Feature | Details |
---|---|
Type | Unpacked, one-dimensional |
Index types | int , string , class |
Memory usage | Sparse — memory allocated only when used |
Use case | Modeling sparse memories, scoreboards, variable tables |
Best methods | .exists() , .num() , .first() , .next() , .delete() |