random c++ question thingy

random c++ question thingy

Post just about everything that isn't directly related to Spring here!

Moderator: Moderators

Post Reply
User avatar
Dragon45
Posts: 2883
Joined: 16 Aug 2004, 04:36

random c++ question thingy

Post by Dragon45 »

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?
User avatar
lurker
Posts: 3842
Joined: 08 Jan 2007, 06:13

Post by lurker »

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.
User avatar
KDR_11k
Game Developer
Posts: 8293
Joined: 25 Jun 2006, 08:44

Post by KDR_11k »

x++ is a post increment, it returns the value x had before being incremented. This also means that once *src is \0 the loop doesn't get executed again so the \0 does not get copied.
User avatar
rattle
Damned Developer
Posts: 8278
Joined: 01 Jun 2006, 13:15

Post by rattle »

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.
Post Reply

Return to “Off Topic Discussion”