Search code examples
cmallocstring-concatenation

Concatenate two strings without using strcat


I wrote a function to concatenate two strings (s = "computer"; t = "keyboard"), but my code only returns "keyboard". Please point out the mistakes.

char *concat(char *s, char *t) {
    s = malloc((strlen(s) + strlen(t) + 1) * sizeof(char));
    char *p = s;
    while (*p != '\0') {
        ++p;
    }
    while (*t != '\0') {
        *p++ = *t++;
    }
    *p = '\0';
    return s;
}

I do not want to use strcat(). This is a test program from Stepik, so I cannot change anything in the main function. Here is the question: Write a function which receives two character pointers and returns a new character pointer representing their concatenation.


Solution

  • char *myconcat(const char *s1, const char *s2)
    {
        size_t len1,len2;
        char *result = malloc((len1 = strlen(s1)) + (len2 = strlen(s2)) + 1);
    
        if(result)
        {
            memcpy(result, s1, len1);
            memcpy(result + len1, s2, len2 + 1);
        }
        return result;
    }