我尝试构建自己的 strdup 函数,因为我知道该函数应该像 strcpy 一样工作,但是可以使用可以在另一个函数中使用的字符串,但是在我的原型中,我不明白为什么我的字符没有被复制。
我已经制作了这个原型,但我不明白为什么我的函数返回的指针不显示我的字符串
char *my_strdup(char *str)
{
char *new_str;
char *to_copy;
int i;
to_copy = str;
i = strlen(str + 1);
new_str = malloc(sizeof(*new_str) * i + 1);
while(i - 1 > 0)
{
*new_str = *to_copy;
new_str++;
to_copy++;
i--;
}
return(new_str);
}
这是我的测试功能:
int main()
{
char *str;
str = my_strdup("helloo");
printf("%s\n", str);
}