hahaha1256
hahaha1256

Reputation: 51

Is there a direct way to concatenate two char arrays (char*)?

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

Answers (2)

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

Nikolay K
Nikolay K

Reputation: 3850

  1. You can do it with std::string

    std::string s1 = "Hello", s2 = "World";
    std::string s3 = s1 + s2;
    const char* c_data = s3.c_str( ); // pointer to char array
    
  2. You can do it with strcat function

Upvotes: 3

Related Questions