An important thing to notice: strcpy
's behavior is undefined (see C99 7.23.2.3:2) when provided with overlapping source and destination. So what you're doing, no matter how the output looks, is basically not guaranteed to work unless your C implementation's documentation states otherwise.
Use memmove
when moving data within a string.
You should also be very careful in how you declare your string. The code you provided is correct:
char string[] = "foo";
The string
is an array of characters, initialized to contain four elements: 'f', 'o', 'o', '\0'.
But, very similar code would be incorrect:
char * string = "foo";
What this code does is initializes a char
pointer to the address of a constant string literal "foo". A correct version would be:
const char * string = "foo";
If you tried to modify such a string, the compiler would rightly complain.