How do I concatenate const/literal strings in C?

前端 未结 17 1785
醉梦人生
醉梦人生 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:21

    If you have experience in C you will notice that strings are only char arrays where the last character is a null character.

    Now that is quite inconvenient as you have to find the last character in order to append something. strcat will do that for you.

    So strcat searches through the first argument for a null character. Then it will replace this with the second argument's content (until that ends in a null).

    Now let's go through your code:

    message = strcat("TEXT " + var);
    

    Here you are adding something to the pointer to the text "TEXT" (the type of "TEXT" is const char*. A pointer.).

    That will usually not work. Also modifying the "TEXT" array will not work as it is usually placed in a constant segment.

    message2 = strcat(strcat("TEXT ", foo), strcat(" TEXT ", bar));
    

    That might work better, except that you are again trying to modify static texts. strcat is not allocating new memory for the result.

    I would propose to do something like this instead:

    sprintf(message2, "TEXT %s TEXT %s", foo, bar);
    

    Read the documentation of sprintf to check for it's options.

    And now an important point:

    Ensure that the buffer has enough space to hold the text AND the null character. There are a couple of functions that can help you, e.g., strncat and special versions of printf that allocate the buffer for you. Not ensuring the buffer size will lead to memory corruption and remotely exploitable bugs.

提交回复
热议问题