c - 指针算术 : warning: assignment makes pointer from integer without a cast [enabled by default]

标签 c pointers warnings pointer-arithmetic

我在学习指针算术时发现了以下代码:

#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/

相关文章:

c - 警告 : assignment makes point from integer without cast

c - 分段默认(核心转储)

c - 在 C 中开始一个新的文本行

c - 暂时在指针中前进

c++ - 初始化指向模板的指针时未解析的外部符号

css - 自定义属性被忽略 : not scoped to the top-level :root element

c - 在不知道字符串大小的情况下动态提示输入字符串

c - C中没有程序输出

c++ - 与删除器共享指针

qt - 如何在 qmake 和 qt5 中包含带有 -isystem(系统头文件)的 Qt 头文件?