void strcpy(char *fin, char *src)
{
while (*src) {
*fin++ = *src++;
}
*fin = '\0';
}
The above code is supposed to copy one string to another; however, im wondering about two things:
1) The src incrementation will work like
*(src++) is assigned to *(fin++);
(Why?) wouldn't the first character be skipped entirely?
2) I recognize that the while loop's condition means that the loop will continue until *src points to "null"/uninit'ed data (essentially until the string ends). However, we're explicitly assign \0 (null-termination character) to the last value of *fin.
If \0 counts as null in a boolean statement then the *fin pointer will never be incremented the last time, and the last non-null char will be overwritten.
If \0 does not count as null in a boolean statement, then things might work out, but the last \0 will still be overwritten (making the \0 completely superfluous).
------------------
So I guess I'm missing something here. Anyone care to enlighten me?
random c++ question thingy
Moderator: Moderators
Note that the ++ comes after the variable name. It's a post-increment, so it's not done until the statement is over. That should directly answer #1, and it also answers #2 indirectly: when src points to a null character for the while check, that null character has not been copied yet, and fin has already been updated to the spot where the new null should be stored.
Code: Select all
void strcpy(char *fin, char *src)
{
while (*src) *++fin = *++src;
*fin = '\0';
}
If your IDE is half-decent you can setup a watch to see what value src and fin have.