Reputation: 51
I know I can construct strings out of them and simply use operator+. But I need to pass the concatenated char array to and old C function so I can't do that.
Upvotes: 1
Views: 1184
Reputation: 40604
If you are interacting with C code, you likely want your strings to be allocated with malloc()
rather than with new
: there is a number of nice functions available in C which produce malloc'ed strings. One of them is asprintf()
, which you can easily use to concatenate your strings:
char* foo = ..., *bar = ..., *result;
asprintf(&result, "%s%s", foo, bar);
baz(result); //Use the concatenated string.
free(result); //cleanup
The nice thing about this approach is, that it is quite safe: Since asprintf()
allocates a buffer to fit your string, there is no danger of overrunning buffers as with strcat()
, strcpy()
, and friends.
Note, however, that even though asprintf()
conforms to the POSIX-2008 standard, it is not part of the C standard, so it's not available everywhere. All Linux systems have it, though.
Upvotes: 0