How do I concatenate const/literal strings in C?

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

    Also malloc and realloc are useful if you don't know ahead of time how many strings are being concatenated.

    #include 
    #include 
    
    void example(const char *header, const char **words, size_t num_words)
    {
        size_t message_len = strlen(header) + 1; /* + 1 for terminating NULL */
        char *message = (char*) malloc(message_len);
        strncat(message, header, message_len);
    
        for(int i = 0; i < num_words; ++i)
        {
           message_len += 1 + strlen(words[i]); /* 1 + for separator ';' */
           message = (char*) realloc(message, message_len);
           strncat(strncat(message, ";", message_len), words[i], message_len);
        }
    
        puts(message);
    
        free(message);
    }
    

提交回复
热议问题