Ready-to-run snippets

Code Examples

Ready-to-run Verilog, SystemVerilog, and UVM examples. Click any to open it live in the IDE.

← All examples

Structure: Array of Structures

SystemVerilog Data Types

Runnable example from the SystemVerilog Structure tutorial (Array of Structures)

Open in IDE
testbench.sv
// Define the structure
typedef struct {
  int data;
  string name;
} MyStruct;

module array_examples;

  // 1. Fixed Array
  MyStruct fixed_array[5];

  // 2. Dynamic Array
  MyStruct dynamic_array[];

  // 3. Associative Array
  MyStruct associative_array[int];

  initial begin
    $display("--- Fixed Array Example ---");
    // Populate the fixed array
    for (int i = 0; i < 5; i++) begin
      fixed_array[i].data = i * 10;
      fixed_array[i].name = $sformatf("Fixed_%0d", i);
      $display("fixed_array[%0d]: data=%0d, name=%s", i, fixed_array[i].data, fixed_array[i].name);
    end

    $display("\n--- Dynamic Array Example ---");
    // Initialize and populate the dynamic array
    dynamic_array = new[3]; // Allocate space for 3 elements

    dynamic_array[0].data = 100;
    dynamic_array[0].name = "Dynamic_A";

    dynamic_array[1].data = 200;
    dynamic_array[1].name = "Dynamic_B";

    dynamic_array[2].data = 300;
    dynamic_array[2].name = "Dynamic_C";

    for (int i = 0; i < dynamic_array.size(); i++) begin
      $display("dynamic_array[%0d]: data=%0d, name=%s", i, dynamic_array[i].data, dynamic_array[i].name);
    end

    $display("\n--- Associative Array Example ---");
    // Populate the associative array using keys
    associative_array[10] = '{101, "Assoc_X"};
    associative_array[25] = '{202, "Assoc_Y"};
	associative_array[5]  = '{303, "Assoc_Z"}; // Keys don't need to be in order

    // Iterating through associative array (keys are returned in sorted order)
    $display("Iterating through associative_array:");
    foreach (associative_array[key]) begin
      $display("associative_array[%0d]: data=%0d, name=%s", key, associative_array[key].data, associative_array[key].name);
    end
  end

endmodule
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.