How do I concatenate two strings in C?

后端 未结 11 1159
春和景丽
春和景丽 2020-11-22 16:00

How do I add two strings?

I tried name = \"derp\" + \"herp\";, but I got an error:

Expression must have integral or enum type

11条回答
  •  天涯浪人
    2020-11-22 16:51

    David Heffernan explained the issue in his answer, and I wrote the improved code. See below.

    A generic function

    We can write a useful variadic function to concatenate any number of strings:

    #include        // calloc
    #include        // va_*
    #include        // strlen, strcpy
    
    char* concat(int count, ...)
    {
        va_list ap;
        int i;
    
        // Find required length to store merged string
        int len = 1; // room for NULL
        va_start(ap, count);
        for(i=0 ; i

    Usage

    #include         // printf
    
    void println(char *line)
    {
        printf("%s\n", line);
    }
    
    int main(int argc, char* argv[])
    {
        char *str;
    
        str = concat(0);             println(str); free(str);
        str = concat(1,"a");         println(str); free(str);
        str = concat(2,"a","b");     println(str); free(str);
        str = concat(3,"a","b","c"); println(str); free(str);
    
        return 0;
    }
    

    Output:

      // Empty line
    a
    ab
    abc
    

    Clean-up

    Note that you should free up the allocated memory when it becomes unneeded to avoid memory leaks:

    char *str = concat(2,"a","b");
    println(str);
    free(str);
    

提交回复
热议问题