需要帮助理解这个用函数模拟strcpy()的C程序吗

需要帮助理解这个用函数模拟strcpy()的C程序吗,c,function,pointers,while-loop,strcpy,C,Function,Pointers,While Loop,Strcpy,这是我的密码。我试图模拟strcpy。这段代码有效,但我有几个问题 #include <stdio.h> #include <stdlib.h> char *strcpy(char *d, const char *s); int main() { char strOne[] = "Welcome to the world of programming!"; char strTwo[] = "Hello world!"; printf("Stri

这是我的密码。我试图模拟strcpy。这段代码有效,但我有几个问题

#include <stdio.h>
#include <stdlib.h>

char *strcpy(char *d, const char *s);

int main()
{
    char strOne[] = "Welcome to the world of programming!";
    char strTwo[] = "Hello world!";
    printf("String One: %s\n", strOne);
    printf("String Two before strcpy(): %s\n", strTwo);
    strcpy(strTwo, strOne);
    printf("String Two after strcpy(): %s\n", strTwo);

    return 0;
}

char *strcpy(char *d, const char *s)
{
   while (*s)
   {
       *d = *s;
       d++;
       s++;
   }
   *d = 0;
   return 0;
}
*d=0时的输出:


ASCII表中的字符假定值范围为0到127,0为空或“\0”,因此除非字符为“\0”,否则该条件始终为真


*d=0在字符串末尾放置“\0”;这是字符串在C中的终止方式。如果不终止字符串,任何内容都可以打印到字符串的末尾,程序无法知道它的结尾。这是未定义的行为。

还有一些评论。返回0而不是指向char的指针。你应该得到一些警告。返回副本。顺便说一句,这个函数也可以简化一点

char *strcpy(char *d, const char *s)
{
   char *saved = d;
   while ((*d++ = *s++));
   return saved;
}

'\0' == 0; '0'==48这看起来像是一个家庭作业堆。为了找到你问题的答案,谷歌“nul终止字符串”以及如何在C中使用true和false。如图所示使用strcpy调用UB。您正在附加到一个没有为额外字符保留空间的数组。你可能会发现它工作得很正常——这可能是UB的结果。你的程序可能会崩溃,或者做一些完全不愉快的事情——这些也是UB的可能结果。现在一切都有意义了。我无法理解*d=0,因为我读错了代码。没有考虑到在while循环中*d已递增,并且while循环没有将\0添加到字符串的末尾。吸取的教训。谢谢你的帮助@苏帕索尼克很乐意帮忙。
String Two before strcpy(): Hello world!                                                                                       
String Two after strcpy(): Welcome to the world of programming! 
char *strcpy(char *d, const char *s)
{
   char *saved = d;
   while ((*d++ = *s++));
   return saved;
}