You can allocate the resulting memory line dynamically (at runtime, on the heap) using new[] in C ++ (or malloc for more C-style):
char* concatStrings(const char* s1, const char* s2, char sep)
Note that this memory must be released somewhere in your code using delete[] if it was allocated using new[] or free() if it was allocated using malloc() .
It is rather complicated.
You will greatly simplify your code if you use a reliable C ++ string class , for example std::string , and its convenient constructors allocate memory, the destructor automatically frees it, and operator+ and operator+= overloads to concatenate strings. See how code is simplified with std::string :
#include <string> // for std::string std::string str = s1; str += sep; str += s2;
(Note that using raw C strings can also make your code more vulnerable to security issues, since you should pay a lot of attention to setting up your target strings correctly, avoid buffer overflows, etc. This is another reason to prefer a reliable RAII class string. e.g. std::string .)
source share