【问题标题】:Copying Array of Char * Corrupts Data复制 Char * 数组会损坏数据
【发布时间】:2012-10-24 08:50:50
【问题描述】:

总的来说,我对 C 语言比较陌生,但我在某些代码方面遇到了问题。这是非常简单的代码:代码的目标是将给定的 char 指针数组或 char **source 复制到给定的 char **destination。

我遇到的问题是有时(通常当我在源中有超过 2 个字符串时)第一个元素完全损坏,当我最终打印出目标时,它会打印出类似“;@?”对于第一个元素,其他元素打印正常。

执行复制的代码是:

void CopyArrayOfStrings(char **source, int numStrings)
{
   char **destination = malloc(numStrings);

    for (int i = 0; i < numStrings; i++)
    {
        destination[i] = malloc(strlen(source[i] + 1);
        strcpy(destination[i], source[i]);
    }
}

请注意,我省略了检查 malloc 的结果是否为 NULL 的代码。

【问题讨论】:

  • 为什么不使用 strdup() 来复制字符串?
  • 我一定错过了 strdup 存在的事实,谢谢!

标签: c pointers copy char corruption


【解决方案1】:

你做错了。

void CopyArrayOfStrings(char **source, int numStrings)
{
   char **destination = malloc(numStrings * sizeof(char *));

    for (int i = 0; i < numStrings; i++)
    {
        destination[i] = malloc(strlen(source[i]) + 1);
        strcpy(destination[i], source[i]);
        //alternatively you can use strdup() as suggested by @Christoffer
    }
}

这将为您提供numStrings 数组的存储空间。其中的每个元素,都将指向一个以空字符结尾的字符串。

【讨论】:

    【解决方案2】:

    您需要将destination 的分配更改为:

    char **destination = malloc(numStrings*(sizeof(char*)));
    

    分配char *指针的数量来保存字符串。

    还要验证您是否正确地将 char ** 作为源字符串数组传递。

    【讨论】:

    • 这个小改动似乎可以正常工作,非常感谢 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    • 2013-03-17
    • 2011-12-16
    • 2012-07-08
    • 2010-09-08
    • 2012-08-01
    • 1970-01-01
    相关资源
    最近更新 更多