Correct way to malloc space for a string and then insert characters into that space?

后端 未结 3 889
太阳男子
太阳男子 2020-12-06 07:11

I have two strings, str1 and str2. I want the concatenation of them on a space in the heap. I malloc space for them using:

char *concat = (char*) malloc(strl         


        
3条回答
  •  孤城傲影
    2020-12-06 07:47

    You want to do a strcpy and then a strcat:

    strcpy(concat, str1);
    strcat(concat, str2);
    

    strcat relies on there being a null terminator ('\0') to know where to begin. If you just malloc and strcat, it's going to do some nasty things.

    And no, neither strcpy nor strcat will do any kind of implicit allocation or reallocation.

提交回复
热议问题