marți, 30 octombrie 2012, 20:00:49 UTC+2, Greg Martin a scris:
> On 12-10-30 10:33 AM, Adrian Sch wrote:
>
> I made a couple of changes to your program. Some to make my compiler
>
> happy, some for readability and one to make the program work. The
>
> pre-increment will return the value after incrementing where as the
>
> post-increment returns it then increments the value. In your version you
>
> begin the to write after the NIL, in mine I overwrite it.
>
>
>
> #include <stdio.h>
>
>
>
> char* strcpy(char* s, char* t) {
>
> while(*++s);
>
>
>
> while((*s++=*t++) != '\0');
>
>
>
> return s;
>
> }
>
>
>
> int main(void) {
>
> char message[100]="string1";
>
> char* message2="string2";
>
>
>
> strcpy(message, message2);
>
> printf("%s\n", message);
>
>
>
> return 0;
>
> }
First, thanks to all of you for the replies.
Second, you are right, this a not-working strcat version.
Third, this is a very subtle problem and quite hard to identify considering my limited knowledge. Because my real question was why the "while(*s++);" gets skiped in the code. Because I was using a debuger and I was expecting some additional action. But because there was no block of code to execute and go back again to the while test, the while test was executed at once (very fast). Am I right or wrong? Because that seemed stupid to me, how the while get skipped while *s was pointing to s.
Now for the real question, that I didn't ask. I figured that the subtlety of the postfix increment is causing my trouble. Because once the *s is pointing at null, it is incremented one more time and the future copies of *t value go after the null. So when I am printing message, I have concatenated the string, but unfortunately after the null, and that makes it just (not random) garbage as far as printf is concerned.
I used a quick hack to fix it: using the prefix operator. That worked! But I think that this is wrong because if the first string's first character was null,then I'd repeat the whole affair from before and have concatenated the string after the null.
Forth, here's the fix(as sugested by some of you):
char *strcpy(char * s, char * t)
{
while(*s)
s++;
while((*s++=*t++))
;
return ;
}
Fifth, Is there any other way to keep simple and elegant, but on just one line of code? Or maybe a messier way, but also to fit in the while testing block? I am thinking and if else shortcut notation, but I don't master the idiom that well to do this apparently.