0

I have char* str1 and char* str2

I wanna concatenate like this res = str1 + str2

strcat(str1, str2) change value of str1, it is not what i need

How to get this result?

3
  • 1
    Then first copy str1 to res, then strcat(res, str2) Commented Feb 10, 2022 at 20:57
  • 2
    ...and always make sure there's enough room for the concatenated string. Commented Feb 10, 2022 at 21:00
  • str1 changed too in my case Commented Feb 10, 2022 at 21:00

1 Answer 1

4

You would have to first copy the first string, and then concatenate the second to that:

strcpy(res, str1); strcat(res, str2); 

... making sure res has enough space allocated for the result, including the null terminator.

Or as a one-liner, if you wish (thanks, Eugene Sh.):

strcat(strcpy(res,str1), str2) 

Another (and safer) option is to use snprintf(), which assures you will not overflow the destination buffer:

int count = snprintf(res, sizeof res, "%s%s", str1, str2); 

If count is less than the size of res minus one, the result was truncated to fit. Note that res must be an array (not decayed to a pointer) for sizeof res to work. If you have another source of the buffer length, you could use that instead.

(snprintf info adapted from user3386109's comment -- thank you!)

Sign up to request clarification or add additional context in comments.

5 Comments

One can even chain these functions strcat(strcpy(res,str1), str2)
better use sprintf
@Jean-François: I don't see how?
@EugeneSh. how does strcpy ensure there's enough space for the concatenated string? That looks very unsafe to me.
@MarkRansom strcpy doesn't, the programmer does (or not..). Sure, it's another way to shoot one's own leg, C provides many of these.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.