将 C 字符串 char by char 复制到动态 char*

Copy c-string char by char to dynamic char*

我有一个 const char* 字符串,我想将该字符串逐个字符地复制到动态 `char*.

const char *constStr = "Hello world";
char *str = (char*) malloc(strlen(constStr)+1);
while(*constStr){
   *str = *constStr;
   constStr++;
   str++;
}
printf("%s", str);
free(str);

问题在于之前的代码只是将 constStr 的每个字符复制到 str 的第一个索引。不知道为什么?

正如其他人指出的那样,您在每次迭代中递增 str 指针,因此您总是最终打印字符串的末尾。

您可以在不增加指针的情况下迭代每个字符。以下代码对我有用:

const char *constStr = "Hello world";
int len = strlen(constStr);
char *str = (char *) malloc(len + 1);
int i;
for (i = 0; i <= len; ++i) {
    str[i] = constStr[i];
}
printf("%s", str);
free(str);

下面是 "classical" 字符串复制解决方案:

const char *constStr = "Hello world";
char *str = malloc(strlen(constStr) + 1), *p = str;
/* Do not forget to check if str!=NULL !*/
while((*p++ = *constStr++));
puts(str);

是的,您没有以 null 终止字符串。这是主要问题。更清楚地说,问题不是你没有用 nul 终止字符串,而是你在预期指向 nul 终止的 char 数组的指针的地方使用它们是问题所在。但即使您这样做了,代码中也存在大量问题。

您分配了内存并强制转换了 malloc 的 return 值,这是不必要的。 void*char* 的转换是隐式完成的。

malloc 可能无法为请求提供服务,它可能 return 一个空指针。重要的是要 检查这个以防止以后尝试取消引用空指针。

然后你开始复制 - 你复制了除了 NUL 终止字符之外的所有内容。然后你将它传递给 printf%s 格式说明符,它需要一个指向空终止字符数组的指针。这是未定义的行为。

str 中的一个位置未初始化 - 请注意访问未初始化的值可能会导致未定义的行为。

还有一个问题,来自标准§7.22.3.3

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

是的,这里是这样吗?不,当您调用 free(str) 时,str 并未指向由 malloc 编辑的动态分配的内存 return。这又是未定义的行为。

解决方案始终是保留一个指针,该指针存储已分配块的地址。其他答案已经显示了它们(不再重复它们 - 它们都提供了一个很好的解决方案)。

您也可以使用 strdupstrcpy - 即使您现在不需要它们 - 习惯它们。它有助于了解这些。是的 strdup 不是标准的一部分,它是 POSIX 标准的东西。

示例:

const char *constStr = "Hello world";
char *str = malloc(strlen(constStr)+1);
if( !str ){
    perror("malloc");
    exit(EXIT_FAILURE);
}
char *sstr = str;
while(*constStr){
   *str = *constStr;
   constStr++;
   str++;
}
*str = 0;
printf("%s", sstr);
free(sstr);

The problem is that previous code just copies each character of constStr to only the first index of the str. I don't know why?

  1. 使用索引变量。
  2. 不要忘记终止“\0”,因为您很有可能出现分段错误。