I am trying to understand how the copying of the dynamic arrays work in SystemVerilog. Here is a small code snippet I was trying:
//dynamic_array
module dyn_array();
//2 dynamic arrays of integer type
int dyn1[];
int dyn2[];
initial
begin
//allocate 5 mem location to dyn1
dyn1 = new[5];
//populate the elements of the dyn array
dyn1 = '{1,2,3,4,5};
$display("the value of dynamic array is %p", dyn1);
//copy method
//method1: entire array elements are deleted and copied into new array
dyn2=dyn1; //they point to the same memory
$display("the value of dynamic array dyn2 is %p", dyn2);
//changing value of element in dyn2
dyn2[2] = 10;
//this change will NOT reflected into dyn1. Why?
//Ideally dyn2 should point to the same memory location in dyn1
//why is the change not reflected in dyn1?
//dyn1 = 1,2,3,4,5, dyn2=1,2,10,4,5
$display("dyn1 after change of dyn2 is %p", dyn1);
$display("dyn2 after change of dyn2 is %p", dyn2);
//the previous elements are erased and it will create 10 locations
dyn1 = new[10];
//dyn1 will be empty 10 element array with 0s
$display("dyn1 after new[10] is %p", dyn1);
//dyn2 will be unchanged- 1,2,10,4,5
$display("dyn2 after new[10] is %p", dyn2);
dyn2 =new[10/*new size*/](dyn2); // 1,2,10,4,5,0,0,0,0,0
$display("dyn1 after new[10](dyn2) is %p", dyn1); //dyn1 should be unchanged
$display("dyn2 after new[10](dyn2) is %p", dyn2);
end
endmodule
Here are the simulation outputs on Modelsim:
# the value of dynamic array is '{1, 2, 3, 4, 5}
# the value of dynamic array dyn2 is '{1, 2, 3, 4, 5}
# dyn1 after change of dyn2 is '{1, 2, 3, 4, 5}
# dyn2 after change of dyn2 is '{1, 2, 10, 4, 5}
# dyn1 after new[10] is '{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
# dyn2 after new[10] is '{1, 2, 10, 4, 5}
# dyn1 after new[10](dyn2) is '{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
# dyn2 after new[10](dyn2) is '{1, 2, 10, 4, 5, 0, 0, 0, 0, 0}
I am not able to understand why after dyn2[2]=10, when I display dyn1, the print says
'{1, 2, 3, 4, 5}
and not
'{1, 2, 10, 4, 5}
on the simulator as I expect dyn1 and dyn2 to share the same memory and any change in dyn2 to be reflected into dyn1.
Could you please explain the behavior in the simulation?