C string concatenation of constants

后端 未结 3 2090
遇见更好的自我
遇见更好的自我 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:44

    #include 
    #include 
    
    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
    

提交回复
热议问题