为什么当我输入一个指针并减去它时会产生错误?

Why is an error is generated when I type cast a pointer and subtract it?

为什么类型转换在这里不起作用..?

#include<stdio.h>
int main(){
   int x = 5;
   float y = 7.0;
   float *p = &y;
   int *q = &x;
   printf("p is %d\nq is %d\np - q is %d", p, q, (p - q));
   return 0;  
  }

我收到这个错误 invalid operands of types 'float*' and 'int*' to binary 'operator-';这是什么意思?

编辑:正如评论中指出的那样,减去两个 void* 指针不是正确的标准 C。如果你想减去两个指针以找到它们之间的距离,正确的方法是将它们转换为适当的大小的整数,然后进行整数运算。

例如:

printf("p is %p\nq is %p\np - q is %ld\n", p, q, ((intptr_t)p - (intptr_t)q));

原回答:

表示没有为混合类型的指针定义减号运算符。如果你想减去这两个指针,例如找到它们之间 space 的数量,更好的选择是将它们都转换为 void* 指针。

此外,您应该使用 %p 说明符而不是 %d 来打印指针值。

例如:

printf("p is %p\nq is %p\np - q is %ld\n", p, q, ((void*)p - (void*)q));

该错误表示编译器无法推断出两个操作数的共同类型,其中一个操作数的类型为 float *,另一个操作数的类型为 int *。这些类型之间没有隐式转换。

但是在任何情况下,程序都有未定义的行为,因为至少你不能减去两个不指向同一数组元素或同一数组最后一个元素之后的内存的指针。

来自 C 标准(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.

并且在函数 printf 中对提供的参数使用不正确的转换说明符(例如 %d 和指针)也会调用未定义的行为。

来自C标准(7.21.6.1 fprintf函数)

9 If a conversion specification is invalid, the behavior is undefined.275) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

我想您想减去指针指向的实际值。 当您对 floatint.

进行操作时,C 会将 int 隐式转换为 float

另外,你的程序也有一些问题

  • 不使用 %f 类型说明符打印 float 指针

  • 不使用 * 运算符访问指针值。

这是您的程序,正在运行:

#include <stdio.h>
int main()
{
    int x = 5;
    float y = 7.0;
    float *p = &y;
    int *q = &x;
    printf("p is %f\nq is %d\np - q is %f", *p, *q, (*p - *q));
    return 0;
}

输出:

p is 7.000000
q is 5
p - q is 2.000000

你不能像那样减去指针并在标准 C 中得到有意义的结果。

根据 6.5.6 Additive operators, paragraph 9 of the C11 standard:

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.

在这种情况下,单个 intfloat 变量被视为大小为 1 的数组。

如此给出

int x = 5;
float y = 7.0;
float *p = &y;
int *q = &x;

尝试计算值 p - q 会导致未定义的行为。

根据 J.2 Undefined behavior:

The behavior is undefined in the following circumstances:

...

  • Pointers that do not point into, or just beyond, the same array object are subtracted

然而,像这样的代码可能不会导致问题,因为它只是减去两个整数值(虽然我没有彻底检查),但结果不一定是有意义的:

int x = 5;
float y = 7.0;
float *p = &y;
int *q = &x;

intptr_t diff = ( intptr_t ) p - ( intptr_t ) q;