以下 c 程序的输出是 1。有人可以解释一下吗?
#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;
}
最佳答案
程序调用了未定义的行为。指针减法必须使用指向同一数组元素的指针来完成。
来自 C 标准:
(C99, 6.5.6p9) "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 [...]"
关于计算并输出两个指针的差值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20800169/