#include <stdio.h>
main() {
int *i,*j;
i = (int *) 60;
j = (int *) 20;
printf("%d\n", i - j);
}
这段代码的输出是什么?我用指针做了很多工作,但从未遇到过这样的代码。
最佳答案
这是未定义的行为,因为您要减去不指向同一数组对象内部的指针。
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.
它也可能是其他原因导致的未定义行为,例如使用指向无效对象的指针。
I am getting an ouput of 10..but couldn't figure out how?
撇开未定义的行为不谈,如果 sizeof(int)
在您的机器上是 4,那么地址 20
和 60< 之间确实有 10 个整数
。这就是指针减法为您提供的:元素数量的差异。
如 teppic
所述,您的 printf 是错误的。 2 个指针之间的差异是 ptrdiff_t
。格式应该类似于 %td
。
关于c - int * 常量转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12228127/