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?

Write a program that asks the user how many values will be entered and then reads all of them. Have the program sort the elements using sort() and then
reverse the sorted elements using reverse().

import std.stdio;
import std.algorithm;

void main() {
    int noValues, i;
    int[] myArray;

    write("how many values would you like to enter? ");
    readf(" %s", &noValues);
myArray.length = noValues; // I get a run-time error if I comment this out

    while (i < noValues) {
        write("enter value #", i+1, " ");
        readf(" %s", &myArray[i]);



Without the line:

myArray.length = noValues;

I get the run-time error:

$ ./exArrays1_1
how many values would you like to enter? 5
core.exception.RangeError@exArrays1_1.d(12): Range violation
??:? _d_arrayboundsp [0x461772]
??:? _Dmain [0x44c284]

I would have thought that since this is a dynamic array, I don't need to pre-assign its length.


Reply via email to