减去两个地址给出错误的输出

减去两个地址给出错误的输出

本文介绍了减去两个地址给出错误的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main()
{
    int x = 4;
    int *p = &x;
    int *k = p++;
    int r = p - k;
    printf("%d %d %d", p,k,p-k);
    getch();
}

输出:

为什么不4?

而且我不能使用p+k或除-(减法)之外的任何其他运算符.

And also I can't use p+k or any other operator except - (subtraction).

推荐答案

首先,您必须为提供的格式说明符使用正确的参数类型,提供不匹配的参数类型会导致未定义的行为.

First of all, you MUST use correct argument type for the supplied format specifier, supplying mismatched type of arguments causes undefined behavior.

  • 您必须使用%p格式说明符并将参数强制转换为void *才能打印地址(指针)

  • You must use %p format specifier and cast the argument to void * to print address (pointers)

要打印指针减法的结果,应使用%td,因为结果的类型为ptrdiff_t.

To print the result of a pointer subtraction, you should use %td, as the result is of type ptrdiff_t.

也就是说,对于减法的结果1,指针算法采用数据类型.引用C11,第6.5.6章,(强调我的)

That said, regarding the result 1 for the subtraction, pointer arithmetic honors the data type. Quoting C11, chapter §6.5.6, (emphasis mine)

因此,在您的情况下,pk的索引相隔一个元素,即|i-J| == 1,因此是结果.

So, in your case, the indexes for p and k are one element apart, i.e, |i-J| == 1, hence the result.

最后,您不能添加(或乘或除)两个指针,因为这是毫无意义的.指针是内存位置,从逻辑上讲,您无法添加两个内存位置.只有减法才有意义,才能找到两个数组成员/元素之间的相关距离.

Finally, you cannot add (or multiply or divide) two pointers, because, that is meaningless. Pointers are memory locations and logically you cannot make sense of adding two memory locations. Only subtracting makes sense, to find the related distance between two array members/elements.

相关约束,来自C11第6.5.6章,加法运算符,

Related Constraints, from C11, chapter §6.5.6, additive operators,

这篇关于减去两个地址给出错误的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 12:46