How do I concatenate const/literal strings in C?

前端 未结 17 1878
醉梦人生
醉梦人生 2020-11-21 23:45

I\'m working in C, and I have to concatenate a few things.

Right now I have this:

message = strcat(\"TEXT \", var);

message2 = strcat(strcat(\"TEXT          


        
17条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 00:26

    The first argument of strcat() needs to be able to hold enough space for the concatenated string. So allocate a buffer with enough space to receive the result.

    char bigEnough[64] = "";
    
    strcat(bigEnough, "TEXT");
    strcat(bigEnough, foo);
    
    /* and so on */
    

    strcat() will concatenate the second argument with the first argument, and store the result in the first argument, the returned char* is simply this first argument, and only for your convenience.

    You do not get a newly allocated string with the first and second argument concatenated, which I'd guess you expected based on your code.

提交回复
热议问题