gpt4 book ai didi

c - 值相同但不相等

转载 作者:行者123 更新时间:2023-11-30 20:01:00 25 4
gpt4 key购买 nike

有人可以向我解释为什么下面的代码输出 0 0 。我的印象是数学上a-b == 0a == b

char* V1 = "hello, world!\n";

main(){
F1(V1);
}

F1(A1){
printf("%u %u\n", V1 - A1, V1 == A1);
}

最佳答案

根据C11标准,第 §6.5.6 章,两个指针只能在来自同一数组对象的情况下相减。

When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements. The size of the result is implementation-defined, and its type (a signed integer type) is ptrdiff_t defined in the <stddef.h> header. If the result is not representable in an object of that type, the behavior is undefined. [...]

也就是说,您应该使用 %td用于打印 ptrdiff_t 类型的结果,由指针减法生成。

接下来,介绍 == 的用法运算符,它不能用于比较字符串(数组)的内容,它基本上比较指针本身(而不是它们指向的内容)。

关于c - 值相同但不相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36604627/

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