Passing dynamic arrays
Jens Mueller
jens.k.mueller at gmx.de
Mon Nov 8 09:30:03 PST 2010
Hi,
I do not understand what's going on behind the scene with this code. Or
better said I have some idea but maybe I do not see the whole point.
void foo(int[] array) {
array.length += 1000; // may copy the array
array[0] = 1;
}
auto a = new int[1];
foo(a);
assert(a[0] == 1); // fails if a needs to copied inside foo
I do understand that array.length += 1000 may copy the array. Page 98 of
The D Programming Language and
http://www.digitalmars.com/d/2.0/arrays.html#resize shed some light on
this matter. Passing a to foo is achieved by copying let's say a begin
and an end pointer. Now due to array.length += 1000 new memory might be
needed and that's why the begin and end pointer change and array[0]
works now on different data. That's why the assert fails. Right?
I find this behavior rather strange. Arrays are neither passed by value
(copying the whole array) nor by reference. I see reasons for doing it
like this, e.g. doing array = array[1..$] inside should not affect the
outside.
But I wonder whether these semantics are well enough documented?
I think I should use ref int[] in the example above, shouldn't I?
Jens
More information about the Digitalmars-d
mailing list