C string concatenation of constants

后端 未结 3 2079
遇见更好的自我
遇见更好的自我 2021-01-03 20:52

One of the answers to Why do you not use C for your web apps? contains the following:

For the C crap example below:

const char* foo = &quo         


        
相关标签:
3条回答
  • 2021-01-03 21:40

    (char*)malloc

    Never typecast the result of malloc in C. Read this and this.

    Actually, constants CAN AND SHOULD be concatenated naturally in C

    No, string literals can and should be concatenated in C. "foo" is a string literal and const char foo[] is a constant string (array of characters). The code "foo" "bar" will concatenate automatically, the code foo bar will not.

    If you want, you can hide the string literals behind macros:

    #define foo "foo"
    #define bar "bar"
    char foobar[] = foo bar; // actually works
    

    So, PLEASE, before you (falsely) claim that C is difficult to use with strings, learn how to use C.

    C is rather difficult to use with strings, as we can see from this very example. Despite their arrogant confidence, the person who wrote it mixed up the various concepts and still has to learn how to use C.

    0 讨论(0)
  • That answer looks like someone managed to conflate string literals, which can be concatenated that way, with const string variables. My guess is the original had preprocessor macros instead of variables.

    0 讨论(0)
  • 2021-01-03 21:44
    #include <stdio.h>
    #include <string.h>
    
    int
    main(int argc, char *argv[])
    {
        char *str1 = "foo";
        char *str2 = "bar";
        char ccat[strlen(str1)+strlen(str2)+1];
    
        strncpy(&ccat[0], str1, strlen(str1));
        strncpy(&ccat[strlen(str1)], str2, strlen(str2));
        ccat[strlen(str1)+strlen(str2)+1] = '\0';
    
        puts(str1);
        puts(str2);
        puts(ccat);
    }
    

    this code concatenates str1 and str2 without the need for malloc, the output should be:

    foo
    bar
    foobar
    
    0 讨论(0)
提交回复
热议问题