开发者

Loop with pointer arithmetic refuse to stay within boundary in C. Gives me segfault

Hi have made this function which is made to replicate an error that I can't get past. It looks like this:

void enumerate(double *c, int size){
    while(c < &c[size]){
            printf("%lf\n", *c);
            c++;
    }

}

I have added some printf's in there and it gives me:

Adressof c: 0x100100080, Adressof c + size: 0x1001000a8

I then also print the address of c for each iteration of the loop, it reaches 0x1001000a8 but continues past this point even though the condition should be false as far as I can tell until I get a segfault. If anyone can spot the problem, please tell me, I have been staring at this for a while now.

开发者_StackOverflow社区

Thanks.


You're using the current value of c in both sides of your loop condition, and you're increasing c every iteration. c will never reach the address of itself plus anything.

Save the address of c[size] before you enter the loop, and you'll eventually reach it.

void enumerate(double *c, int size) {
    double *addr = &c[size];
    while(c < addr) {
            printf("%lf\n", *c);
            c++;
    }
}


The problem is the condition checking itself....

while(c < &c[size])

Withing the while loop you are incrementing c.

So both c and &c[size] will go on incrementing, since the second address is relative to the current value of c.

A better way would be :

void enumerate(double *c, int size){
    double *ptr = c;
    while(c < &ptr[size]){
            printf("%lf\n", *c);
            c++;
    }
}


Each time you reach c++, the value of &c[size] also changes. So, the condition is always true.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜