www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Array indexing

reply "js.mdnq" <js_adddot+mdng gmail.com> writes:
When accessing an element outside a dynamic array I get an 
exception.

I thought in D arrays will automatically expand themselves?

If not, how do I add an element to an array?

int[] arr = new int[1];
arr[1] = 34; // exception

If I change this to

int[] arr = new int[2];
arr[1] = 34;

Then it works. (similar to C/C++)

But my arrays will be growing and I do not know the final size 
ahead of time.

arr.add(34) does not work.
Dec 03 2012
next sibling parent "Adam D. Ruppe" <destructionator gmail.com> writes:
Try

arr ~= 33;

the ~= operator means append to. You can also do

auto a = [1,2] ~ [3,4];

which would give [1,2,3,4]
Dec 03 2012
prev sibling next sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
js.mdnq:

 When accessing an element outside a dynamic array I get an 
 exception.

 I thought in D arrays will automatically expand themselves?

D dynamic arrays don't expand themselves "on demand" on array access, it's not efficient (and I think it's not a very clean operation, despite some languages do it). On the other hand D associative arrays grow if you add them key-values.
 arr.add(34) does not work.

To append to a dynamic array use: arr ~= 34; Bye, bearophile
Dec 03 2012
prev sibling parent =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
On 12/03/2012 04:43 PM, js.mdnq wrote:
 When accessing an element outside a dynamic array I get an exception.

 I thought in D arrays will automatically expand themselves?

 If not, how do I add an element to an array?

 int[] arr = new int[1];
 arr[1] = 34; // exception

Another option is to modify the length of the "slice" (yes, "slice", not "array"): arr.length = 100; The following is almost mandatory reading: :) http://dlang.org/d-array-article.html Ali
Dec 03 2012