noob Q: array out-of-range

bearophile bearophileHUGS at lycos.com
Fri May 28 14:54:32 PDT 2010


Don:
> The array initially has length of zero.
> You need to write something like:
> intArray = new int[3];
> or
> intArray.length = 3;
> before putting anything into it.

In some languages (Perl? Maybe Lua and PHP) arrays auto-create empty slots as needed, but in many languages you need to tell the language that you want some empty slots before you can put values inside them (this stricter behaviour can probably catch some bugs, and allows to produce faster programs).

Another way to add items to a D dynamic array like intArray is to append them at the end, the language runtime takes care of creating new slots as needed:

int[] intArray;
intArray ~= 1;
intArray ~= 2;
intArray ~= 3;

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list