Arrays passed by almost reference?
    Frank Benoit 
    keinfarbton at googlemail.com
       
    Thu Nov  5 13:18:39 PST 2009
    
    
  
Ali Cehreli schrieb:
> I haven't started reading Andrei's chapter on arrays yet. I hope I won't find out that the following behavior is expected. :)
> 
> import std.cstream;
> 
> void modify(int[] a)
> {
>     a[0] = 1;
>     a ~= 2;
> 
>     dout.writefln("During: ", a);
> }
> 
> void main()
> {
>     int[] a = [ 0 ];
> 
>     dout.writefln("Before: ", a);
>     modify(a);
>     dout.writefln("After : ", a);
> }
> 
> The output with dmd 2.035 is
> 
> Before: [0]
> During: [1,2]
> After : [1]
> 
> I don't understand arrays. :D
> 
> Ali
> 
int[] a;
a is kind of a pointer, one with the extra length information.
When passed to modify(), a is passed by-value, the contained data is
certainly passed by-reference since a points to the data.
This is why the a.length was not updated.
If you change "modify" to :
void modify(ref int[] a){...
it should work as you expected.
    
    
More information about the Digitalmars-d
mailing list