Fixed length vs dynamic arrays

Paul Backus snarwin at gmail.com
Sat May 8 00:52:03 UTC 2021


On Friday, 7 May 2021 at 22:21:09 UTC, Alain De Vos wrote:
> Following code compiles without errors, only errors during 
> runtime
> ```
> int main(){
> 	int[2]  a=new int[2];
> 	int[]   b=new int[0];
> 	int[2]  c=[1,2];
> 	a=a~3;
> 	b=b~3;
> 	c=c~3;
> 	c=b;
> 	b=a;
> 	a=c;
> return 0;
> }
> ```

The result of a `~` expression is always a newly-allocated 
dynamic array on the GC heap. [1]

When you assign a dynamic array to a static array, the elements 
from the dynamic array on the right-hand side are copied into the 
static array on the left-hand side. [2] So the statement

     a = a ~ 3;

...is essentially shorthand for

     auto _tmp = a ~ 3;
     foreach (i; 0 .. _tmp.length)
         a[i] = _tmp[i];

Because `a` has length `2` and `a ~ 3` has length `3`, this 
results in a `RangeViolation` at runtime when attempting to copy 
`_tmp[2]` into `a[2]`.

[1] https://dlang.org/spec/expression.html#cat_expressions
[2] https://dlang.org/spec/arrays.html#array-copying


More information about the Digitalmars-d-learn mailing list