Search code examples
cwhile-loopc-stringsfunction-definitionstrcat

Concat two strings through pointers not working


I made a function that concat string t to the end of string s, for my exercise I have to use pointers for this, so I did this way but its not working:

#include <stdio.h>

void strcat(char *s, char *t)
{
    while (*s++);

    for (*s = *t; *s = *t; s++, t++);
}

int main()
{
    char c[100] = "hello";
    char *w = " world\n";
    
    strcat(c, w);

    printf(c);
    
    return 0;
}

The output of c always return "hello" instead of "hello world\n"


Solution

  • This while loop within the function

    while (*s++);
    

    is incorrect. After the while loop the pointer s points to after the terminating zero character '\0' due to the postfix increment operator.

    The function can be declared and defined the following way

    char * strcat(char *s, const char *t)
    {
        char *p = s;
    
        while( *p ) ++p;
    
        while ( ( *p++ = *t++ ) != '\0' );
    
        return s;
    }
    

    Also you should rename the function because there is already standard string function strcat in C.

    Here is a demonstration program.

    #include <stdio.h>
    
    char *string_cat( char *s, const char *t )
    {
        char *p = s;
    
        while (*p) ++p;
    
        while (( *p++ = *t++ ) != '\0');
    
        return s;
    }
    
    int main( void )
    {
        char c[100] = "hello";
        const char *w = " world";
    
        puts( string_cat( c, w ) );
    }
    

    The program output is

    hello world