简体   繁体   中英

Strange pointer behaviour in loop

I can't figure out why is this code not working. (I know how to fix it, but I'm interested in this particular solution) It takes one string and puts is on the end of other string. x = "abc" , y = "def" and after executing foo, x = "abcdef" . After executing my code I only get "abc" .

#include <stdio.h>
#define MAX 10

void foo(char *x, char *y){
    while(*x++);
    while(*y){
        *x++ = *y++;
    }
    *x = '\0';
}

int main(void){
    char x[MAX+1], y[MAX+1];
    scanf("%s %s", x, y);
    foo(x, y);
    printf("%s", x);
    return 0;
}

If I do this, the code works perfectly fine.

while(*x) x++;

This expression will increment x even after the null is discovered and the loop completes:

while(*x++);

In this case, you are appending the second string AFTER the null, so that part of the string isn't "seen". The string becomes "abc\\0def" .

The following will NOT increment x when the null is found, so *x will point to null after the loop completes:

while(*x) x++;

Therefore, in this case, your string comes out correctly as, "abcdef" .

This loop:

while(*x++);

moves x past the null terminator. So your c-string ends at the same place as it did before. The characters in y are written to x , but they come after the null terminator, so they are not printed out.

When you use

while(*x++);

x points to one past the null character at the end of the statement. In effect, you end up with

x[] = {'a', 'b', 'c', '\0', 'd', 'e', 'f', '\0', ....}

in main .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM