How do I concatenate const/literal strings in C?

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

    Do not forget to initialize the output buffer. The first argument to strcat must be a null terminated string with enough extra space allocated for the resulting string:

    char out[1024] = ""; // must be initialized
    strcat( out, null_terminated_string ); 
    // null_terminated_string has less than 1023 chars
    
    0 讨论(0)
  • 2020-11-22 00:24

    This was my solution

    #include <stdlib.h>
    #include <stdarg.h>
    
    char *strconcat(int num_args, ...) {
        int strsize = 0;
        va_list ap;
        va_start(ap, num_args);
        for (int i = 0; i < num_args; i++) 
            strsize += strlen(va_arg(ap, char*));
    
        char *res = malloc(strsize+1);
        strsize = 0;
        va_start(ap, num_args);
        for (int i = 0; i < num_args; i++) {
            char *s = va_arg(ap, char*);
            strcpy(res+strsize, s);
            strsize += strlen(s);
        }
        va_end(ap);
        res[strsize] = '\0';
    
        return res;
    }
    

    but you need to specify how many strings you're going to concatenate

    char *str = strconcat(3, "testing ", "this ", "thing");
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 00:27

    As people pointed out string handling improved much. So you may want to learn how to use the C++ string library instead of C-style strings. However here is a solution in pure C

    #include <string.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    void appendToHello(const char *s) {
        const char *const hello = "hello ";
    
        const size_t sLength     = strlen(s);
        const size_t helloLength = strlen(hello);
        const size_t totalLength = sLength + helloLength;
    
        char *const strBuf = malloc(totalLength + 1);
        if (strBuf == NULL) {
            fprintf(stderr, "malloc failed\n");
            exit(EXIT_FAILURE);
        }
    
        strcpy(strBuf, hello);
        strcpy(strBuf + helloLength, s);
    
        puts(strBuf);
    
        free(strBuf);
    
    }
    
    int main (void) {
        appendToHello("blah blah");
        return 0;
    }
    

    I am not sure whether it is correct/safe but right now I could not find a better way to do this in ANSI C.

    0 讨论(0)
  • 2020-11-22 00:28

    In C, "strings" are just plain char arrays. Therefore, you can't directly concatenate them with other "strings".

    You can use the strcat function, which appends the string pointed to by src to the end of the string pointed to by dest:

    char *strcat(char *dest, const char *src);
    

    Here is an example from cplusplus.com:

    char str[80];
    strcpy(str, "these ");
    strcat(str, "strings ");
    strcat(str, "are ");
    strcat(str, "concatenated.");
    

    For the first parameter, you need to provide the destination buffer itself. The destination buffer must be a char array buffer. E.g.: char buffer[1024];

    Make sure that the first parameter has enough space to store what you're trying to copy into it. If available to you, it is safer to use functions like: strcpy_s and strcat_s where you explicitly have to specify the size of the destination buffer.

    Note: A string literal cannot be used as a buffer, since it is a constant. Thus, you always have to allocate a char array for the buffer.

    The return value of strcat can simply be ignored, it merely returns the same pointer as was passed in as the first argument. It is there for convenience, and allows you to chain the calls into one line of code:

    strcat(strcat(str, foo), bar);
    

    So your problem could be solved as follows:

    char *foo = "foo";
    char *bar = "bar";
    char str[80];
    strcpy(str, "TEXT ");
    strcat(str, foo);
    strcat(str, bar);
    
    0 讨论(0)
提交回复
热议问题