简体   繁体   English

在C中串联两个字符串

[英]Concatenating two strings in C

So I have to make a function to concatenate two strings in C; 因此,我必须创建一个函数以在C中连接两个字符串。 The function creates a new string by concatenating str1 and str2. 该函数通过连接str1和str2创建一个新字符串。 The function has to call malloc() or calloc() to allocate memory for the new string.The function returns the new string. 该函数必须调用malloc()或calloc()为新字符串分配内存。该函数返回新字符串。

After executing the following call to printf() in a main test function: printf ( “%s\\n”, myStrcat( “Hello”, “world!” )); 在主测试函数中执行对printf()的以下调用之后:printf(“%s \\ n”,myStrcat(“ Hello”,“ world!”)); the printout on the screen has to be Helloworld! 屏幕上的打印输出必须是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. 您将返回final_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) : 您应该将malloc的结果存储在另一个变量中(应该始终对失败进行测试):

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; 因此,名称final_string很不幸; make it perhaps current_pointer ! 使其成为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 特别是您的main职能

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

is a memory leak (you never free the result of that my_strcat call, but you should). 内存泄漏 (您永远不会free my_strcat调用的结果,但应该这样做)。

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. 请养成使用警告和调试信息进行编译的习惯(例如gcc -Wall -Wextra -gGCC ),并学习如何使用调试器( gdb ),因为可以在调试器中逐步执行程序。 Use also valgrind to detect -by testing- some memory leaks. 还可以使用valgrind通过测试来检测一些内存泄漏。

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 您可以随时使用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. final_string指向目标字符串的末尾。

Following code returns the final string: 以下代码返回最终字符串:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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