Appending the array space to already existing multidimensional dynamic array

This is the code I wrote and I only get 5x3 = 15 spaces whereas the intention is to have
5x(2+3) = 25 total space

module dynamic_array;
    int arr[][];
    int apple = 10;
    
    initial begin
        
      arr = new[5];
      
      foreach(arr[i])begin
          arr[i] = new[2];
          arr[i] = new[3] (arr[i]);  //Expected that this would give arr[i][5] but didn't
      end
      
      foreach(arr[i,j])begin
        arr[i][j] = apple + 5;
        apple += 5;
        $display("arr[%0d][%0d] = %0d",i,j,arr[i][j]);
      end
      
    end
endmodule

output:

arr[0][0] = 15
arr[0][1] = 20
arr[0][2] = 25
arr[1][0] = 30
arr[1][1] = 35
arr[1][2] = 40
arr[2][0] = 45
arr[2][1] = 50
arr[2][2] = 55
arr[3][0] = 60
arr[3][1] = 65
arr[3][2] = 70
arr[4][0] = 75
arr[4][1] = 80
arr[4][2] = 85

The dynamic array constructor new[N] destroys the existing array and reallocates a new array with the size N. The statement

    arr[i] = new[3] (arr[i]);

creates an array with 3 elements and then copies the values of what was in the 2 elements of arr[i] into the first 2 elements of the new array. Since all values are initially 0, this doesn’t actually do anything.

If you want to increase the size of an existing dynamic array, you have to replace it with a new array with the desired size.

arr[i] = new[arr[i].size()+3];
arr[i] = {arr[i],0,0,0}; // or use an array concatenation

Note that if you need to repeatedly change the size of a dynamic array, it might be more efficient to use a queue instead.

1 Like

But while reading about dynamic arrays, I read:
Resizing of an array and copy old array content can be done as shown below:

dyn_arr = new[a];
dyn_arr = new[a] (dyn_arr);

is that not right?

Sumeet,

There is a small typo there.

dyn_arr = new[a];
dyn_arr = new[b] (dyn_arr);

When you do resize by the above method, the size is adjusted from a → b. So you will have a new size (b), means the existing array (a) contents copied to new array(of size b), and the old array is cleaned up.
‘b’ is the new size.

Kranthi

1 Like

Thanks, Dave and Kranthi.
Ok, so the below gives me resizing and adding new values

module dynamic_array;
    int dyn_arr[];
    
    initial begin
      dyn_arr = new[5];
      
      foreach(dyn_arr[i])begin
        dyn_arr[i] = 15;
      end
      
      dyn_arr = new[10] (dyn_arr);
      
      foreach(dyn_arr[i])begin
        if(dyn_arr[i] == 0)
           dyn_arr[i] = 10;
      end
      
      foreach(dyn_arr[i])begin
        $display("dyn_arr[%0d] = %0d",i,dyn_arr[i]);
      end
    end
endmodule

Output:
dyn_arr[0] = 15
dyn_arr[1] = 15
dyn_arr[2] = 15
dyn_arr[3] = 15
dyn_arr[4] = 15
dyn_arr[5] = 10
dyn_arr[6] = 10
dyn_arr[7] = 10
dyn_arr[8] = 10
dyn_arr[9] = 10

1 Like