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++;
source to share
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"
.
source to share