Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D2: setting array dimensions at runtime

Tags:

d

How do you set the dimension of an array when you don't yet know it at compile time?

For instance: byte[][] a = new byte[size][size]; The compiler does not allow it. How am I supposed to initialize the grid? Manually?

byte[] a1;
for (int i; i < size; i++) {
     a1 ~= 0;
} 
byte[][] a2; 
for (int i; i < size; i++) {
     a2 ~= a1;
} 

Please tell me there is a simpler way.

Edit: this also works, but it is still hopelessly primitive, and slow

byte[][] a3; 
a3.length = size;
for (int i; i < size; i++) {
     a3[i].length = size;
} 
like image 819
fwend Avatar asked Dec 05 '10 16:12

fwend


1 Answers

Don't going into depths, here is an example of initializing multidimensional dynamic array in D:

auto a = new int[][](4, 4);

Edit: here goes more complete example (showing that you can initialize array during runtime to avoid confusion):

int x = 3, y = 4, z = 5;
auto a = new byte[][][](x, y, z);

Stdout(a[0][0].length).newline; // prints 5
a[0][0].length = 10;
Stdout(a[0][0].length).newline; // prints 10
like image 170
barti_ddu Avatar answered Oct 21 '22 23:10

barti_ddu