Static initialization of static arrays is weird

Dennis dkorpel at gmail.com
Sun Aug 19 11:20:41 UTC 2018


I have a two dimensional static array in a game board struct and 
want to explicitly set the default value for each cell. Now 
typing the whole 9x9 array out would be cumbersome and I can't 
change the default constructor of a struct, so I played around 
with initializers and found some... strange behavior.

Demo:
```
import std.stdio: writeln;

struct T {
     int[3][3] arr = [2, 1];
     this(int stub) {
         arr[0][0] = 9;
     }
}

void main() {
     T.init.writeln;
     T(0).writeln;
}
```
Output:
```
T([[2, 1, 0], [0, 0, 118033674], [723976, 0, 4100]])
T([[9, 2, 2], [1, 1, 1], [0, 0, 0]])
```
So it seems that in the .init value, it puts [2, 1] in the first 
array and the rest is garbage. But in the constructor case, it 
filled the first two static arrays with 2 and 1 and the other one 
is 0 / garbage (can't tell). I turned to the spec:

https://dlang.org/spec/arrays.html#static-init-static

But that doesn't really help specify this case. Should I submit a 
bugzilla issue? I don't know what's supposed to happen here.

And in the mean time, what's the easiest way to initialize a (2d) 
static array with a value?


More information about the Digitalmars-d-learn mailing list