文字列を複製してから値を連結したいとします。
stl std::string を使用すると、次のようになります。
string s = "hello" ;
string s2 = s + " there" ; // effectively dup/cat
Cで:
char* s = "hello" ;
char* s2 = strdup( s ) ;
strcat( s2, " there" ) ; // s2 is too short for this operation
Cでこれを行う唯一の方法は次のとおりです。
char* s = "hello" ;
char* s2=(char*)malloc( strlen(s) + strlen( " there" ) + 1 ) ; // allocate enough space
strcpy( s2, s ) ;
strcat( s2, " there" ) ;
Cでこれを行うよりエレガントな方法はありますか?