Concatenate two char* strings in a C program

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

    strcat attempts to append the second parameter to the first. This won't work since you are assigning implicitly sized constant strings.

    If all you want to do is print two strings out

    printf("%s%s",str1,str2);
    

    Would do.

    You could do something like

    char *str1 = calloc(sizeof("SSSS")+sizeof("KKKK")+1,sizeof *str1);
    strcpy(str1,"SSSS");
    strcat(str1,str2);
    

    to create a concatenated string; however strongly consider using strncat/strncpy instead. And read the man pages carefully for the above. (oh and don't forget to free str1 at the end).

提交回复
热议问题