我想追加两个字符串.我使用以下命令:
new_str = strcat(str1, str2);
Run Code Online (Sandbox Code Playgroud)
此命令更改的值str1
.我想new_str
成为concatanation的str1
,并str2
在同一时间str1
将不被改变.
Cha*_*tin 61
您还需要分配新空间.考虑以下代码片段:
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?
}
Run Code Online (Sandbox Code Playgroud)
您可能想要考虑strnlen(3)
哪个稍微安全一些.
更新,见上文.在C运行时的某些版本中,返回的内存malloc
未初始化为0.将第一个字节设置new_str
为零可确保它看起来像strcat的空字符串.
请执行下列操作:
strcat(new_str,str1);
strcat(new_str,str2);
Run Code Online (Sandbox Code Playgroud)
考虑使用伟大但未知的 open_memstream() 函数。
FILE *open_memstream(char **ptr, size_t *sizeloc);
用法示例:
// open the stream
FILE *stream;
char *buf;
size_t len;
stream = open_memstream(&buf, &len);
// write what you want with fprintf() into the stream
fprintf(stream, "Hello");
fprintf(stream, " ");
fprintf(stream, "%s\n", "world");
// close the stream, the buffer is allocated and the size is set !
fclose(stream);
printf ("the result is '%s' (%d characters)\n", buf, len);
free(buf);
Run Code Online (Sandbox Code Playgroud)
如果您事先不知道要追加的内容的长度,这比自己管理缓冲区方便且安全。