Concatenating strings in C, which method is more efficient?

后端 未结 10 920
迷失自我
迷失自我 2020-11-28 19:51

I came across these two methods to concatenate strings:

Common part:

char* first= \"First\";
char* second = \"Second\";
char* both = malloc(strlen(fi         


        
10条回答
  •  温柔的废话
    2020-11-28 20:46

    size_t lf = strlen(first);
    size_t ls = strlen(second);
    
    char *both = (char*) malloc((lf + ls + 2) * sizeof(char));
    
    strcpy(both, first);
    
    both[lf] = ' ';
    strcpy(&both[lf+1], second);
    

提交回复
热议问题