C字符串附加

Uda*_*age 43 c string

我想追加两个字符串.我使用以下命令:

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的空字符串.

  • `malloc`总能返回垃圾,甚至在现代系统上也是如此.`calloc`为你提供归零内存. (12认同)
  • 并且calloc通常也需要sizeof(space)时间来完成它.如果你正在做很多字符串并且你的指针很小心,你可以节省大量的冗余指令. (2认同)
  • 请删除不正确的猜想:"我相信较新的C规范实际上要求malloc这样做".此外,将第一个字节设置为零使其成为零长度字符串(不是看起来像). (2认同)

Vir*_*oll 6

请执行下列操作:

strcat(new_str,str1);
strcat(new_str,str2);
Run Code Online (Sandbox Code Playgroud)

  • 需要注意的是,new_str必须初始化为空字符串. (4认同)
  • 适当的大小!! (4认同)
  • 当 new_str 不能容纳空间或 (*new_str) != 0 时,这会崩溃 (2认同)
  • 这一直给我“分段错误” (2认同)

Chr*_*ard 6

考虑使用伟大但未知的 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)

如果您事先不知道要追加的内容的长度,这比自己管理缓冲区方便且安全。

  • 值得注意的是,“open_memstream”是 POSIX 的一部分,而不是 ISO C 标准。因此,它不适用于非 Unix 系统(例如 Windows),甚至不适用于所有 Unix 系统。`strcat` 是一个更便携的解决方案。 (2认同)