On 10/30/2012 1:33 PM, Adrian Sch wrote:
> Hello! I am doing some exercises from K&R 2nd edition and I seem to be stuck: Here's a working copy of a custom strcpy:
>
> char *strcpy(char * s, char * t)
> {
>
> char x;
> while(x=*s)
> s++;
>
> while((*s++=*t++))
> ;
>
> return ;
> }
That's not a strcpy() work-alike. Looks more like strcat(),
which is a different breed of, well, cat.
> And here's a version that doesn't work:
> char *strcpy(char * s, char * t)
> {
>
> while(*s++)
> ;
>
> while((*s++=*t++))
> ;
>
> return ;
> }
This isn't a work-alike for any of the standard string
functions, and certainly not for strcpy() or strcat(). A name
like strabut() might describe what it does, which is: "Copy the
`t' string to the memory area just after the `s' string, leaving
the '\0' at the end of `s' undisturbed."
I think what you've overlooked is that the test in the first
`while' loop will detect the '\0' character *and* will advance
`s' past that character. If you want to append the `t' characters
to `s', you should deposit the first of them right where the '\0'
was originally; as things stand, you're depositing that first
character just after the '\0'.
--
Eric Sosman
d