Concatenate two char* strings in a C program

后端 未结 6 1874
梦如初夏
梦如初夏 2020-12-15 06:38

I wrote the following C program:

int main(int argc, char** argv) {

    char* str1;
    char* str2;
    str1 = \"sssss\";
    str2 = \"kkkk\";
    printf(\"%         


        
6条回答
  •  再見小時候
    2020-12-15 07:07

    Here is a working solution:

    #include 
    #include 
    
    int main(int argc, char** argv) 
    {
          char str1[16];
          char str2[16];
          strcpy(str1, "sssss");
          strcpy(str2, "kkkk");
          strcat(str1, str2);
          printf("%s", str1);
          return 0;
    }
    

    Output:

    ssssskkkk
    

    You have to allocate memory for your strings. In the above code, I declare str1 and str2 as character arrays containing 16 characters. I used strcpy to copy characters of string literals into them, and strcat to append the characters of str2 to the end of str1. Here is how these character arrays look like during the execution of the program:

    After declaration (both are empty): 
    str1: [][][][][][][][][][][][][][][][][][][][] 
    str2: [][][][][][][][][][][][][][][][][][][][]
    
    After calling strcpy (\0 is the string terminator zero byte): 
    str1: [s][s][s][s][s][\0][][][][][][][][][][][][][][] 
    str2: [k][k][k][k][\0][][][][][][][][][][][][][][][]
    
    After calling strcat: 
    str1: [s][s][s][s][s][k][k][k][k][\0][][][][][][][][][][] 
    str2: [k][k][k][k][\0][][][][][][][][][][][][][][][]
    

提交回复
热议问题