Foreach Access Violation
BCS
ao at pathlink.com
Mon Oct 20 09:13:15 PDT 2008
Reply to nobody,
> Apple[] apples;
>
> for(int i = 0; i < 10; i++)
> {
> apples.length = apples.length + 1;
> apples[apples.length-1] = new Apple();
> }
Apple[] apples = new Apples[10];
for(int i = 0; i < 10; i++)
{
apples[apples.length-1] = new Apple();
}
The above would be faster in many cases. Extending length often results in
a new allocation and must check to see if it needs to do one every time.
If I just want to accumulate things but don't know in advance how many there
will be I over allocate by a bit, keep track of how many you have used externally
and slice it back down once your done.
> This generally works fine, except when the last apple is deleted.
> Then I get an Access Violation Error in the foreach loop.
> When I use a for loop instead it works perfectly.
> Is this because the foreach loop doesn't reevalute the length of the
> apples
> array
> while looping, or am I missing something else entirely?
IIRC the docs say is it illegal to alter the loop array inside of a foreach
More information about the Digitalmars-d-learn
mailing list