简体   繁体   中英

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.

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;
}

You have s="computer" when passed into a function, and then on the very first line you reassign it with malloc, so "computer" is gone. You can debug your program step by step, or just print the values to the console. This will help you to find the error.

You are on the right track:

  • you allocate the correct amount of memory,
  • you copy the second string correctly,
  • you set the null terminator correctly,
  • you return the pointer to the allocated block.

Yet there are some issues:

  • you overwrite the pointer to the first string with that returned by malloc() ,
  • you read from the allocated memory block instead of copying the first string: this has undefined behavior,
  • (minor) the argument strings should be declared as const char * as you do not modify these strings.

Here is a corrected version:

#include <stdlib.h>
#include <string.h>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM