是否有一个简洁的方法来strdup()后跟strcat()?

bob*_*obo 5 c c-strings

假设我想复制一个字符串,然后将值连接到它.

使用stl std :: string,它是:

string s = "hello" ;
string s2 = s + " there" ; // effectively dup/cat
Run Code Online (Sandbox Code Playgroud)

在C:

char* s = "hello" ;
char* s2 = strdup( s ) ; 
strcat( s2, " there" ) ; // s2 is too short for this operation
Run Code Online (Sandbox Code Playgroud)

我知道在C中执行此操作的唯一方法是:

char* s = "hello" ;
char* s2=(char*)malloc( strlen(s) + strlen( " there" ) + 1 ) ; // allocate enough space
strcpy( s2, s ) ;
strcat( s2, " there" ) ;
Run Code Online (Sandbox Code Playgroud)

在C中有更优雅的方法吗?

orl*_*rlp 5

你可以做一个:

char* strcat_copy(const char *str1, const char *str2) {
    int str1_len, str2_len;
    char *new_str;

    /* null check */

    str1_len = strlen(str1);
    str2_len = strlen(str2);

    new_str = malloc(str1_len + str2_len + 1);

    /* null check */

    memcpy(new_str, str1, str1_len);
    memcpy(new_str + str1_len, str2, str2_len + 1);

    return new_str;
}
Run Code Online (Sandbox Code Playgroud)