Strange pointer behavior in a loop

I cannot figure out why this code is not working. (I know how to fix this, but I'm interested in this specific solution). It takes one line and puts at the end of another line. x = "abc"

, y = "def"

And after 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 fine.

while(*x) x++;

      

+3


source to share


3 answers


This expression will increment x

even after detecting a null value and completing the loop:

while(*x++);

      

In this case, you add the second line AFTER the null value, so that part of the line is not displayed. The string becomes "abc\0def"

.



Below will NOT increment x

at zero, so it *x

will point to zero after the loop ends:

while(*x) x++;

      

So in this case your string is outputting correctly like "abcdef"

.

+12


source


This loop:

while(*x++);

      



moves x

behind the zero terminator. This way your c-line ends at the same place as before. The characters in are y

written to x

, but they appear after the null terminator, so they are not printed.

+6


source


When you use

while(*x++);

      

x

indicates one minus null character at the end of the statement. In fact, you get

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

      

in main

.

+1


source







All Articles