Why is dynamic array length required here?
Stanislav Blinov
stanislav.blinov at gmail.com
Fri Oct 19 02:18:07 UTC 2018
On Friday, 19 October 2018 at 02:04:37 UTC, Samir wrote:
> I am working my way through the exercises in the "Programming
> in D" tutorial (http://ddili.org/ders/d.en/arrays.html). Why
> is the line assigning the length of the dynamic array required?
[...]
>
> Without the line:
>
> myArray.length = noValues;
>
> I get the run-time error...
> I would have thought that since this is a dynamic array, I
> don't need to pre-assign its length.
Even though the array is dynamic, it doesn't have infinite
storage. So you either:
- preallocate required storage, like in that example code (note
that it's not the same as making a fixed-size ('static') array:
in your case you only learn what the required length is at
run-time, as opposed to static arrays where you must know it at
compile time)
- don't preallocate, but instead append new elements like this:
myArray ~= newValue;
The latter isn't a universally "good" advice: it may cause
reallocation every time you do that. That's why it's almost
always best to preallocate in advance if you do know the length,
or use something like std.array.appender that attempts to reduce
memory reallocation. I'm not familiar with Ali's tutorials, maybe
he talks about the appender in some future examples.
More information about the Digitalmars-d-learn
mailing list