首页 > 解决方案 > 需要帮助理解这个用函数模拟 strcpy() 的 C 程序

问题描述

这是我的代码。我正在尝试模拟 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;
}
  1. 当 *s 递增到数组中存储 '\0' 的位置时,是不是因为 '\0' 而 while 条件变为假?while 读取 '\0' 还是只是 '0'?

  2. 如果读取为“1”,则“while”条件将为真。*s 的所有先前值都应在 while 条件中读取为单个字符,但循环仍会执行。为什么会这样?数组 *s 中的所有单个字符是否都指向值“1”?

  3. 具体是做什么*d = 0;的?我理解的方式是,当退出while循环时,复制过程就完成了。那么为什么删除*d = 0会导致显示不正确的输出呢?

输出没有*d = 0

String Two before strcpy(): Hello world!                                                                                       
String Two after strcpy(): Welcome to the world of programming! programming! 

输出*d = 0

String Two before strcpy(): Hello world!                                                                                       
String Two after strcpy(): Welcome to the world of programming! 

标签: cfunctionpointerswhile-loopstrcpy

解决方案


ASCII 表中的字符假定值范围从01270NULL'\0',因此除非字符是 ,否则条件始终为真'\0'

*d = 0将 a'\0'放在字符串的末尾;这就是字符串在 C 中的终止方式。如果您不终止字符串,则可以打印超出字符串末尾的任何内容,并且程序无法知道它在哪里结束。这是未定义的行为。


推荐阅读