Search code examples
ccharstrcat

C char* + char* concatenation


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?


Solution

  • 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!)