C string append

后端 未结 10 1315
野趣味
野趣味 2020-12-01 06:21

I want to append two strings. I used the following command:

new_str = strcat(str1, str2);

This command changes the value of str1

10条回答
  •  南笙
    南笙 (楼主)
    2020-12-01 06:37

    You need to allocate new space as well. Consider this code fragment:

    char * new_str ;
    if((new_str = malloc(strlen(str1)+strlen(str2)+1)) != NULL){
        new_str[0] = '\0';   // ensures the memory is an empty string
        strcat(new_str,str1);
        strcat(new_str,str2);
    } else {
        fprintf(STDERR,"malloc failed!\n");
        // exit?
    }
    

    You might want to consider strnlen(3) which is slightly safer.

    Updated, see above. In some versions of the C runtime, the memory returned by malloc isn't initialized to 0. Setting the first byte of new_str to zero ensures that it looks like an empty string to strcat.

提交回复
热议问题