digitalmars.D.learn - Fixed length vs dynamic arrays
- Alain De Vos (3/3) May 06 2021 Is a fixed length array created on the heap and a dynamic array
- Paul Backus (11/14) May 06 2021 Static arrays (`T[N]`) are value types, like structs. If you
- Alain De Vos (15/15) May 07 2021 Following code compiles without errors, only errors during runtime
- Paul Backus (16/32) May 07 2021 The result of a `~` expression is always a newly-allocated
Is a fixed length array created on the heap and a dynamic array on the stack ? And is this important with relation to the garbage collector ?
May 06 2021
On Thursday, 6 May 2021 at 22:35:38 UTC, Alain De Vos wrote:Is a fixed length array created on the heap and a dynamic array on the stack ? And is this important with relation to the garbage collector ?Static arrays (`T[N]`) are value types, like structs. If you declare them as local variables, they're allocated on the stack. Dynamic arrays (`T[]`), also known as slices, are reference types, consisting of a pointer and a length. If you declare them as local variables, the pointer and length will be stored on the stack. The data they point to, however, may be stored on either the stack or the heap. For more information about slices in D, I highly recommend this excellent article by Steven Schveighoffer: https://dlang.org/articles/d-array-article.html
May 06 2021
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; } ```
May 07 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
May 07 2021