How do I concatenate two strings in C?

后端 未结 11 1170
春和景丽
春和景丽 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:40

    Without GNU extension:

    #include 
    #include 
    #include 
    
    int main(void) {
        const char str1[] = "First";
        const char str2[] = "Second";
        char *res;
    
        res = malloc(strlen(str1) + strlen(str2) + 1);
        if (!res) {
            fprintf(stderr, "malloc() failed: insufficient memory!\n");
            return EXIT_FAILURE;
        }
    
        strcpy(res, str1);
        strcat(res, str2);
    
        printf("Result: '%s'\n", res);
        free(res);
        return EXIT_SUCCESS;
    }
    

    Alternatively with GNU extension:

    #define _GNU_SOURCE
    #include 
    #include 
    #include 
    
    int main(void) {
        const char str1[] = "First";
        const char str2[] = "Second";
        char *res;
    
        if (-1 == asprintf(&res, "%s%s", str1, str2)) {
            fprintf(stderr, "asprintf() failed: insufficient memory!\n");
            return EXIT_FAILURE;
        }
    
        printf("Result: '%s'\n", res);
        free(res);
        return EXIT_SUCCESS;
    }
    

    See malloc, free and asprintf for more details.

提交回复
热议问题