我在学习指针算术
时发现了以下代码:
#include <stdio.h>
int main()
{
int *p, *q, *r, a, b;
p = &a;
q = &b;
p = p-q;
r = &a;
r = (int*)(r-q);
printf("p = %p\n",p);
printf("r = %p\n",r);
}
当我编译代码时,我收到以下警告:
test.c:7:11: warning: assignment makes pointer from integer without a cast [enabled by default]
p = q-p;
^
现在,当我运行代码时,我得到以下输出:
p = 0x1
r = 0x1
由于输出相同,任何人都可以解释一下警告的重要性。预先感谢您。
最佳答案
从地址中减去地址,不会返回地址。它返回整数,即这些地址之间的距离。
N1570 - 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; 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. ...
关于c - 指针算术 : warning: assignment makes pointer from integer without a cast [enabled by default],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25845930/