减去两个地址给出错误的输出 [英] subtracting two addresses giving wrong output

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

问题描述

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

输出:

2752116 2752112 1

2752116 2752112 1

为什么不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)

当减去两个指针时,两个指针都应指向同一数组对象的元素, 或在数组对象的最后一个元素之后; 结果是 这两个数组元素的下标.结果的大小是实现定义的, 及其类型(带符号整数类型)是在<stddef.h>标头中定义的ptrdiff_t . [....]如果表达式PQ分别指向 如果是数组对象,则表达式(P)-(Q)的值应为i−j,前提是该值适合类型为ptrdiff_t的对象. [....]

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. [....] if the expressions P and Q point to, respectively, the i-th and j-th elements of an array object, the expression (P)-(Q) has the value i−j provided the value fits in an object of type ptrdiff_t. [....]

因此,在您的情况下,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,

此外,两个操作数都应具有算术类型,或者一个操作数应为a 指向完整对象类型的指针,另一个应具有整数类型. (递增是 等同于添加1.)

For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to a complete object type and the other shall have integer type. (Incrementing is equivalent to adding 1.)

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆