简体   繁体   中英

Concatenating two strings in C

So I have to make a function to concatenate two strings in C; The function creates a new string by concatenating str1 and str2. The function has to call malloc() or calloc() to allocate memory for the new string.The function returns the new string.

After executing the following call to printf() in a main test function: printf ( “%s\\n”, myStrcat( “Hello”, “world!” )); the printout on the screen has to be Helloworld!

Here's my code so far; I can't quite understand why it does not work. It doesn't do anything... it compiles and runs but nothing is displayed.

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

char *my_strcat( const char * const str1, const char * const str2);

int main()
{
    printf("%s", my_strcat("Hello", "World")); // test function. Output of print statement    is supposed to be HelloWorld
}

char *my_strcat( const char * const str1, const char * const str2)
{

    char *temp1 = str1; // initializing a pointer to the first string
    char *temp2 = str2; // initializing a pointer to the second string

    // dynamically allocating memory for concatenated string = length of string 1 + length of string 2 + 1 for null indicator thing.
    char *final_string = (char*)malloc (strlen(str1) + strlen(str2) + 1);

    while (*temp1 != '\0') //while loop to loop through first string. goes as long as temp1  does not hit the end of the string
    {
        *final_string = *temp1; // sets each successive element of final string to equal each successive element of temp1
        temp1++; // increments address of temp1 so it can feed a new element at a new address
        final_string++; // increments address of final string so it can accept a new element at a new address
    }
    while (*temp2 != '\0') // same as above, except for string 2.
    {
        *final_string = *temp2;
        temp2++;
        final_string++;
    }

    *final_string = '\0'; // adds the null terminator thing to signify a string
    return final_string; //returns the final string.
}

You're returning final_string , but it's been incremented during the course of your algorithm to point to the null terminator - not the beginning of the string.

You need to change the allocation to something like:

char *final_string_return = malloc(strlen(str1) + strlen(str2) + 1);
char *final_string = final_string_return;

And then later on:

return final_string_return;

You should store in another variable the result of malloc (which you should always test against failure) :

char *result_string = malloc (strlen(str1) + strlen(str2) + 1); 
if (!result_string) { perror("malloc"); exit(EXIT_FAILURE); };
final_string = result_string;

and finally return it

return result_string;

So the name final_string is unfortunate; make it perhaps current_pointer !

BTW, your function is working only with the convention that the caller should free its result. You should document that convention (at least in comments). In particular in your main function

printf("%s", my_strcat("Hello", "World"));

is a memory leak (you never free the result of that my_strcat call, but you should).

Please take the habit of compiling with warnings and debug info (eg gcc -Wall -Wextra -g with GCC ), and learn how to use the debugger ( gdb ), since you could step by step your program in the debugger. Use also valgrind to detect -by testing- some memory leaks.

int main( void )
{
    char * concatStr = my_strcat("Hello", "World");

    printf("%s", concatStr); // test function. 
    // Output of print statement    is supposed to be HelloWorld
    free( concatStr ); // note this is safe, even if my_strcat() returns NULL
    return(0);
}

char *my_strcat( const char * const str1, const char * const str2)
{


    // dynamically allocating memory for concatenated string 
    // = length of string 1 + length of string 2 + 1 for null indicator thing.
    // and sets all bytes to '\0'
    char *final_string = calloc ((strlen(str1) + strlen(str2) + 1), 1);
    if( NULL == final_string )
    { // then calloc() failed
        return( NULL );
    }
    // implied else, calloc() successful

    strcpy( final_string, str1 );
    strcat( final_string, str2 );

    return( final_string ); // note: caller must invoke free() 
                            //       to avoid memory leak.
}

You can always just use sprintf

char* my_strcat(const char* const s1, const char* const s2)
{
    char *dst = malloc(strlen(s1) + strlen(s2) + 1);
    if (dst == NULL)
    {
      return NULL;
    }
    sprintf(dst, "%s%s", s1, s2);
    return dst;
}

The final_string points to the end of destination string.

Following code returns the final string:

return (final_string-strlen(str1)-strlen(str2)-1); //returns the final string.

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