开发者

Loop executing infinite times

开发者 https://www.devze.com 2023-02-06 05:10 出处:网络
Could you please tell me what the error could be? for (int开发者_如何学编程 r=[list count]-1; r>=0;r--) {

Could you please tell me what the error could be?

for (int开发者_如何学编程 r=[list count]-1; r>=0;r--) {
            NSMutableArray *temp;
            temp=[list objectAtIndex:r];
            [list insertObject:temp atIndex:r++];
        }

At the first call, [list count] is 2.


You're incrementing your loop variable r inside the loop, so it can never decrement to zero.

You need to change this line:

        [list insertObject:temp atIndex:r++];

to perhaps:

        [list insertObject:temp atIndex:r + 1];


You have an infinite loop because the loop starts passing the test (r == 1 && 1 >= 0) and from that point, r never changes. You simply grab the object at r (1) and insert it at r (1) and then increment r (r == 2). Finally, the loop ends, r gets decremented (r == 1) and you run your test again (1 >= 0 ) so it runs the loop and the exact same thing happens.

You probably want to insert temp at the next index (r + 1) but that will cause a crash since your array has only 2 places. You would need to do an addObject: in order to increase the size of the array (and to insert the item at r + 1 in this case).


Paul’s right. Maybe you think that r++ is a shorthand for r+1? It’s not, it means r=r+1.

0

精彩评论

暂无评论...
验证码 换一张
取 消