C语言 复制字符指针内容的函数在打印副本的第二个索引时崩溃



我在将字符指针指向的内容复制到另一个内容时遇到问题,即使我在使用 strcpy 之前为其分配了内存。我已经看到了 strdup 的肮脏建议,但我想知道在不需要的情况下该怎么做。这是我的主要代码

int main (void)
{
    char word[20];
    leaftype destiny;
    while(1)
    {
        printf("nType in a word: ");
        scanf("%s",word);
        copy_leaf(&destiny,palavra);
        if (palavra[0] == '0') break;
    }
    system("pause");
    return 0;
}

我遇到的问题是函数copy_leaf:

void copy_leaf(leaftype* destiny, leaftype source)
{
    printf("n====start of copy_leaf======n");
    int i;
    printf("strlen of source: %d",strlen(source));
    printf("nsource: ");
    for(i = 0; i <= strlen(source); i++)
    {
        if(i == strlen(source))
        {
            printf("\0");
        }
        else printf("%c-",source[i]);
    }
    *destiny = malloc((strlen(source)+1)*sizeof(char));
    strcpy(*destiny,source);
    printf("nstrlen of destiny: %d",strlen(*destiny));
    printf("ndestiny: ");
    for(i = 0; i <= strlen(*destiny); i++)
    {
        if(i == strlen(*destiny))
        {
        printf("\0");
        }
        else printf("%c-",*destiny[i]);
    }
    printf("n===end of copy_leaf======n");
}

叶类型定义为:

typedef char* leaftype;

当我运行以"example"一词作为输入的代码时,我在控制台上:

Type in a word: 
====start of copy_leaf======
strlen of source: 7
source: e-x-a-m-p-l-e-
strlen of destiny: 7
destiny: e-

并且它崩溃("程序.exe已停止工作等"在 Windows 7 上(。我正在使用devcpp,但我的文件以C扩展名命名。任何人都可以帮助我修复此字符*到字符*内容副本吗?我需要一个函数来做到这一点,因为我需要在 C 文件中多次将一个字符串的内容复制到另一个字符串。提前感谢!

附言:我已经在copy_leaf功能(绝望的解决方案(中尝试过:

    将叶类型源更改为常量
  • 叶类型源(这将是常量字符*源(
  • 使 *destiny = strcpy(*destiny,source(,因为 strcpy 返回指向目标字符串的指针

你不应该使用*destiny[i],但你需要使用(*destiny)[i],就像这一行一样,

    else printf("%c-",(*destiny)[i]);

顺便说一句,命运是双指针,我认为你真的不需要双指针。

printf("%c-",*destiny[i]);

destiny 是字符**,[] 优先于 *。

因此,这被解释为:

printf("%c-",*(destiny[i]));

当您真正想要时:

printf("%c-", (*destiny)[i]);

即,您正在读取第 i 个指针的第一个元素,而您实际上想要第一个(也是唯一的(指针的第 i 个元素。

为什么我喜欢这样?这些是要完成的以下更正。

 void copy_leaf(leaftype* destiny, leaftype source)

更改为

void copy_leaf(leaftype destiny, leaftype source)
destiny = malloc((strlen(source)+1)*sizeof(char));
strcpy(destiny,source);

for(i = 0; i < strlen(destiny); i++)
    {
        printf("%c-",destiny[i]);

    }

顺便说一下,strcpy 的正确原型应该是源数据应该始终是 - const char *。

最新更新