Say I wanted to duplicate a string then concatenate a value to it.
Using stl std::string, it’s:
string s = "hello" ;
string s2 = s + " there" ; // effectively dup/cat
in C:
char* s = "hello" ;
char* s2 = strdup( s ) ;
strcat( s2, " there" ) ; // s2 is too short for this operation
The only way I know to do this in C is:
char* s = "hello" ;
char* s2=(char*)malloc( strlen(s) + strlen( " there" ) + 1 ) ; // allocate enough space
strcpy( s2, s ) ;
strcat( s2, " there" ) ;
Is there a more elegant way to do this in C?
You could make one: