I'm writing my own version of strcat in C following K&R. This is my code:
#define MAXVALUE 1000
void concat(char *s, char *t)
{
while (*s++)
;
while (*s++ = *t++)
;
}
/* test */
int main()
{
char s1[MAXVALUE];
char s2[] = "Jim!";
s1[0] = 'H', s1[1] = 'i', s1[2] = ' ';
s1[3] = '\0';
concat(s1, s2);
printf("%s\n", s1);
return 0;
}
The idea is to copy s2 into s1 to obtain "Hi Jim!". I made sure that s1 is large enough to contain both strings. However, when I run this, it outputs "Hi", so basically it does not update the string s1. I'm at a loss as to why: s1 still points at s1[0] = 'H' and after running concat the '\0' in s1[3] should have been replaced and s1 should be terminated with '\0' at s1[7].
P.S. Note that as in K&R, my version of strcat does not match the standard library one. In particular, the return value is void.
In your code, the problem is, after reaching the terminating
NUL, you're advancing the pointer*s++, so, it is included in the destination string, making theprintf()to interpret as the end of string. As per the design rule of string concatination, you need to remove [or replace, or overwrite] the terminatingNULand add the second string.To avoid the terminating
NULapperaing in the output string, do not increment the pointer when it reachesNUL, instead, start copying the next string from that particular location itself.Check the below code.