passing pointer to strcat does not update the string

171 views Asked by At

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.

3

There are 3 answers

0
Sourav Ghosh On

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 the printf() to interpret as the end of string. As per the design rule of string concatination, you need to remove [or replace, or overwrite] the terminating NUL and add the second string.

To avoid the terminating NUL apperaing in the output string, do not increment the pointer when it reaches NUL, instead, start copying the next string from that particular location itself.

Check the below code.

#include <stdio.h>
#include <stdlib.h>

#define MAXVALUE 1000

void concat(char *s, char *t)
{
    while (*s)  s++;     //after NUL, do not increment, move on to copying
    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;
}
0
Gopi On

Check the below code:

void concat(char *s, char *t) 
{
       while (*s != '\0')
          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;
}
3
teagut On

Thanks to @MOehm, I fixed the code by simply inserting s-- to compensate for going past the null terminator:

void concat(char *s, char *t)
{
    while (*s++)
        ;
    s--;
    while (*s++ = *t++)
        ;
}