I can't get passing an array by reference to work anymore...

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Sep 24 21:14:01 PDT 2015


On Friday, 25 September 2015 at 02:37:22 UTC, TheGag96 wrote:
> What's the problem here? I SWEAR I've passed arrays by 
> reference before just like this. Thanks guys.

I'm seeing the same error, but I haven't yet determined why. At 
any rate, this works:

```
import std.stdio;

void append(ref int[] arr, int val) {
     arr ~= val;
}

void main() {
     auto a1 = [10,20,30];
     a1.append(40);
     writeln(a1);
}
```

The compiler error aside, there's a big difference between this 
function and your quicksort. This one is modifying the structure 
(or metadata) of the source array. Your quicksort is only dealing 
with the elements. You don't need to use ref to effect changes on 
the elements of the source array. arr[1] = 2 on a function 
parameter will be reflected in the source array even when ref is 
absent. Only when you need to modify the length of the source 
array, or cause it to point to a new memory block, would you need 
to use ref.

So in your particular case, you can drop the ref from your 
parameter and the compiler error will go away. However, the 
function as written is producing a range violation :)

I'd still like to know what's causing the compiler error with ref 
in this case, though.


More information about the Digitalmars-d-learn mailing list