gpt4 book ai didi

c - 同类指针的区别

转载 作者:行者123 更新时间:2023-12-04 23:52:07 25 4
gpt4 key购买 nike

相同类型的两个指针的差总是一个。

#include<stdio.h>
#include<string.h>
int main(){
int a = 5,b = 10,c;
int *p = &a,*q = &b;
c = p - q;
printf("%d" , c);
return 0;
}

Output is 1.

我不明白背后的原因

最佳答案

行为未定义。

C99 6.5.6 第 9 段说:

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.

同一节第 7 段说:

For the purposes of these operators, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.

第 4 节第 2 段说:

If a "shall" or "shall not" requirement that appears outside of a constraint is violated, the behavior is undefined. Undefined behavior is otherwise indicated in this International Standard by the words "undefined behavior" or by the omission of any explicit definition of behavior. There is no difference in emphasis among these three; they all describe "behavior that is undefined".

3.4.3 将术语“未定义行为”定义为:

behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International imposes no requirements

NOTE Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

鉴于声明:

int a = 5, b = 10, c;

很可能评估 &b - &a 会产生一个看起来合理的结果,例如 1-1。 (合理的结果总是未定义行为的可能征兆;它是未定义的,不需要崩溃。)但编译器没有义务将 ab 放在任何特定位置内存中相对于彼此的位置,即使这样做,减法也不能保证有意义。优化编译器可以自由地以假设其行为定义明确的方式转换您的程序,如果违反该假设,代码将以任意糟糕的方式运行。

通过编写 &b - &a,您实际上是在向编译器 promise 这是一个有意义的操作。正如 Henry Spencer 的名言,“如果你对编译器撒谎,它就会报复。”

请注意,不只是减法的结果是未定义的,它是评估它的程序的行为


哦,我有没有提到行为是未定义的?

关于c - 同类指针的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8957040/

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