c - 需要帮助理解这个用函数模拟 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;
}
当 *s 递增到数组中存储 '\0' 的位置时,是不是因为 '\0' 而 while 条件变为假?while 读取 '\0' 还是只是 '0'?
如果读取为“1”,则“while”条件将为真。*s 的所有先前值都应在 while 条件中读取为单个字符,但循环仍会执行。为什么会这样?数组 *s 中的所有单个字符是否都指向值“1”?
具体是做什么
*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!
解决方案
ASCII 表中的字符假定值范围从0
到127
、0
是NULL
或'\0'
,因此除非字符是 ,否则条件始终为真'\0'
。
*d = 0
将 a'\0'
放在字符串的末尾;这就是字符串在 C 中的终止方式。如果您不终止字符串,则可以打印超出字符串末尾的任何内容,并且程序无法知道它在哪里结束。这是未定义的行为。
推荐阅读
- node.js - webpack 4 使用 nodejs api - 不创建供应商块
- c# - 在.NET Core 中排除模型中的主键,因为 SQL 在 INSERT 时生成 PK
- functional-programming - 如何在 FP 中构造组件?
- javascript - Vue js 与 CDN 类型的 Javascript 文件集成
- node.js - 将 node_modules 文件夹放在单独的文件夹中
- apache - 无法从 apache solr 获取记录
- php - stdClass 无法转换为字符串
- firebase - 如何将验证码发送到电子邮件 ID
- python-3.x - RPLY - 具有多行代码的意外令牌解析源代码
- python - 用 Python Click 编写的 CLI 响应慢