Concatenate two char* strings in a C program

后端 未结 6 1873
梦如初夏
梦如初夏 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:23

    The way it works is to:

    1. Malloc memory large enough to hold copies of str1 and str2
    2. Then it copies str1 into str3
    3. Then it appends str2 onto the end of str3
    4. When you're using str3 you'd normally free it free (str3);

    Here's an example for you play with. It's very simple and has no hard-coded lengths. You can try it here: http://ideone.com/d3g1xs

    See this post for information about size of char

    #include 
    #include 
    
    int main(int argc, char** argv) {
    
          char* str1;
          char* str2;
          str1 = "sssss";
          str2 = "kkkk";
          char * str3 = (char *) malloc(1 + strlen(str1)+ strlen(str2) );
          strcpy(str3, str1);
          strcat(str3, str2);
          printf("%s", str3);
    
          return 0;
     }
    

提交回复
热议问题