why static array can be reassigned with new allocation?

jfondren julian.fondren at gmail.com
Fri Oct 14 19:46:06 UTC 2022


On Friday, 14 October 2022 at 18:57:44 UTC, mw wrote:
> Why this code can be compiled and causing runtime error? it 
> should be caught at compile time!

```d
import std.stdio;

void main() {
     int[3] arr;
     writeln(arr.ptr);
     arr = new int[3];
     writeln(arr.ptr);
     writeln(typeid(arr));
}
```

output (e.g.):

```
7FFD5EBF1530
7FFD5EBF1530
int[3]
```

It's not a reassignment of arr, but a copying of the contents of 
the dynamic array, and it crashes with an oversized array as the 
lengths don't match, same as if you did

```d
     int[] other = new int[5];
     foreach (i; 0 .. other.length)
         arr[i] = other[i];
```


More information about the Digitalmars-d mailing list