const char* concatenation


I need to concatenate two const chars like these:

const char *one = "Hello ";
const char *two = "World";

How might I go about doing that?

I am passed these char*s from a third-party library with a C interface so I can't simply use std::string instead.

1/4/2010 1:10:15 AM

Accepted Answer

In your example one and two are char pointers, pointing to char constants. You cannot change the char constants pointed to by these pointers. So anything like:

strcat(one,two); // append string two to string one.

will not work. Instead you should have a separate variable(char array) to hold the result. Something like this:

char result[100];   // array to hold the result.

strcpy(result,one); // copy string one into the result.
strcat(result,two); // append string two to the result.
1/4/2010 5:18:06 AM

The C way:

char buf[100];
strcpy(buf, one);
strcat(buf, two);

The C++ way:

std::string buf(one);

The compile-time way:

#define one "hello "
#define two "world"
#define concat(first, second) first second

const char* buf = concat(one, two);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow