lital maatuk
lital maatuk

Reputation: 6239

connecting chars*

How would I connect to char* strings to each other. For example:

char* a="Heli";
char* b="copter";

How would I connect them to one char c which should be equal to "Helicopter" ?

Upvotes: 3

Views: 6420

Answers (4)

Tony Delroy
Tony Delroy

Reputation: 106086

If your system has asprintf() (pretty common these days), then it's easy:

char* p;
int num_chars = asprintf(&p, "%s%s", a, b);

The second argument is a format string akin to printf(), so you can mix in constant text, ints, doubles etc., controlling field widths and precision, padding characters, justification etc.. If num_chars != -1 (an error), then p then points to heap-allocated memory that can be released with free(). Using asprintf() avoids the relatively verbose and error-prone steps to calculate the required buffer size yourself.

In C++:

std::string result = std::string(a) + b;

Note: a + b adds two pointers - not what you want, hence at least one side of the + operator needs to see a std::string, which will ensure the string-specific concatenation operator is used.

(The accepted answer of strncat is worth further comment: it can be used to concatenate more textual data after an ASCIIZ string in an existing, writeable buffer, in-so-much as that buffer has space to spare. You can't safely/portably concatenate onto a string literal, and it's still a pain to create such a buffer. If you do it using malloc() to ensure it's exactly the right length, then strcat() can be used in preference to strncat() anyway.)

Upvotes: 3

PrettyPrincessKitty FS
PrettyPrincessKitty FS

Reputation: 6400

In C++:

std::string foo(a);
std::string bar(b);
std::string result = foo+bar;

Upvotes: 3

datenwolf
datenwolf

Reputation: 162164

size_t newlen = strlen(a) + strlen(b);
char *r = malloc(newlen + 1);
strcpy(r, a);
strcat(r, b);

Upvotes: 6

robert
robert

Reputation: 34398

strncat

Or use strings.

Upvotes: 8

Related Questions