Foreach Access Violation

bearophile bearophileHUGS at lycos.com
Mon Oct 20 15:42:35 PDT 2008


More comments added to the answers given by the other people.

nobody:
> Several apples are created:
> Apple[] apples;
> for(int i = 0; i < 10; i++)
> {
>     apples.length = apples.length + 1;
>     apples[apples.length-1] = new Apple();
> }

If you know you want 10 apples then this is better (D2, but in D1 it's similar):

auto apples = new Apple[10];
foreach (ref apple; apples)
    apple = new Apple();

If you don't know how many you will have:

Apple[] apples;
foreach (i; 0 .. find_number())
    apples ~= new Apple();

Finally if you don't know how many you will have, but you know they can be a lot, then you can use an array appender, like the one discussed recently.


> foreach(int i, Apple apple; apples)
> {
>      apples.iterate();
> }

Note this suffices here:

foreach(apple; apples)
{
    apples.iterate();
}

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list