gpt4 book ai didi

c - 为什么 '\0'在使用指针时等同于0?

转载 作者:太空宇宙 更新时间:2023-11-04 01:07:55 25 4
gpt4 key购买 nike

我正在从 K&R 书中学习 C,在第 5 章中它展示了 strcpy() 的实现,其中涉及指针(而不是使用数组索引)。它说:

while ((*s++ = *t++) != '\0')

while (*s++ = *t++)

两者做同样的事情,!= '\0' 部分不是必需的。但我不完全明白为什么。 '\0' 当指向该空字符的指针被取消引用时是否等于零?

*编辑:所以如果 '\0' 等于零,那么这也有效吗? *

while (s[i] = t[i]) i++; 

最佳答案

Both do the same thing, and that the != '\0' part is not necessary. But I don't completely understand why.

因为在 C 语言中,在需要条件表达式的地方,非 0 数字(整数和浮点值)和非 NULL 指针被解释为 true,零 NULL 被认为是错误的。但这与您问题的第二部分没有任何关系。

Is '\0' equivalent to zero when a pointer pointing to that null character is dereferenced or something?

在任何上下文中,它总是等同于0。即使您执行 void *foo = '\0';,它也会将 foo 设置为 NULL,因为整数文字零是合适的指针的初始值设定项,并将其转换为 NULL。但我不明白你为什么要问指针,因为你只是将积分与积分进行比较(charint 都是积分类型)。

关于c - 为什么 '\0'在使用指针时等同于0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19305258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com