Arrays, copied or referenced?

BCS ao at pathlink.com
Sun Aug 5 15:33:29 PDT 2007


Reply to Audun,

> Hey..
> 
> Take this code:
> --------------------------
> import std.stdio;
> int[] arrayTest(int[] a) {
> a.length = 5;
> a[4] = 42;
> return a;
> }
> int main(char[][] args) {
> int[10] foobar;
> foobar[4] = 2;
> arrayTest(foobar);
> writefln("%d", foobar[4]);
> return 0;
> }
> --------------------------
> It prints out "42".
> Now replace the line "a.length = 20", and it prints out "2".
> Is that the way it's supposed to behave?
> 
> Audun Wilhelmsen
> NTNU, Norway

The assignment to length forces a reallocation of the array, Until then 'a' 
is a reference of the data from the parent. After that you have a reference 
to a new array.





More information about the Digitalmars-d mailing list