What am I doing wrong ?

Mike Wey mike-wey at example.com
Sun Apr 22 14:55:52 PDT 2012


On 04/22/2012 11:47 PM, SomeDude wrote:
> Sorry for the noob questions, but
>
> import std.stdio;
>
> struct Foo {
> int x;
> }
> void main() {
> auto array = new Foo[10];
> auto i = array.length;
> foreach(Foo f; array) { f.x = --i; write(f.x);}

Use ref when you want to modify the original array, without ref you are 
modifying a copy in the foreach.

foreach(ref Foo f; array) { f.x = --i; write(f.x);}

> writeln();
> foreach(Foo f; array) { write(f.x);}
> }
>
> gives me:
>
> PS E:\DigitalMars\dmd2\samples> rdmd bug.d
> 9876543210
> 0000000000
>
> Also,
>
> void main() {
> auto array = new Foo[10];
> --> for(int i = array.length; i > 1; i--) { array[i].x = i; }
> writeln();
> foreach(Foo f; array) { write(f.x);}
> }
>
> throws core.exception.RangeError at bug(8): Range violation on the line
> with the arrow.
>
> What am I doing wrong ?

You set i to the array length of 10 but the array index is zero based so 
the last item in the array is at index 9.
But in the first iteration of the loop you are trying to access the the 
item at index 10 (array.length) which doesn't exist.

-- 
Mike Wey


More information about the Digitalmars-d-learn mailing list