2
votes

I am trying to return dynamic array from function, i did dome job but i dont know how to do that fully dynamic, which mean without declare the "data_len" thanks for helping,

module test1();

typedef integer dyn_arr[];

function dyn_arr get_register_name();
    int data_len = 3;
    get_register_name = new [data_len] ;
    get_register_name[0] = 5;
    get_register_name[1] = 2;

endfunction

 dyn_arr my_q;

  initial begin
       my_q = get_register_name();
      $display("%d",my_q[1]);
      $display("%d",my_q[0]);
  end

endmodule
2
Did you mean without variable declaration inside function? you can pass the size of dynamic array as argument to the function check this - Emman
What do you mean by "fully dynamic" an array is either fixed, or dynamically sized. There is no in-between. - dave_59
Perhaps you want a queue or associative array? - Greg

2 Answers

2
votes

You can pass the dynamic array by reference in the function for your purpose.

Here is the sample code for it.

module tp();
  integer a[];

  initial
  begin
    return_x(a);
    $display("a - %p", a);
  end
endmodule

function automatic void return_x(ref integer x[]);
  x = new [3];
  x = '{3,3,3};
endfunction

// Output - 
// a - '{3, 3, 3}
1
votes

If you want to return the dynamic array using return in your function, then you need a typedef.

Typedef is needed when you want a function to return an unpacked type.

e.g.

typedef int registerdynamic_t[];
function automatic  registerdynamic_t return_dyn_arr get_register_name(int data_len=2);       
    return_dyn_arr = new [data_len] ;
    //you can use a for loop to put values in your dynamic array
    return_dyn_arr [0] = 5;
    return_dyn_arr [1] = 2;
    return return_dyn_arr ;
endfunction