C中两个指针相减时 [英] When subtracting two pointers in C

查看:51
本文介绍了C中两个指针相减时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我玩指针是为了完全理解这个概念,然后想减去两个指针,期望这两个地址之间的距离或其他东西,但显然我错了,所以这是我的代码.

I was playing with pointers in order to fully get the concept and then wanted to subtract two pointers expecting the distance between these two addresses or something, but apparently I was wrong, so here is my code.

int x = 5, y = 7;
int *p = &y;
int *q = &x;
printf("p is %d\nq is %d\np - q is %d", p, q, (p - q));

为什么程序输出p - q is 1?谢谢.

Why does the program output p - q is 1? Thank you.

推荐答案

这是未定义的行为.根据标准(N1570):

It is undefined behavior. According to the standard (N1570):

6.5.6 加法运算符
....
9 两个指针相减时,都应该指向同一个数组对象的元素,或超过数组对象的最后一个元素;结果是的差异两个数组元素的下标.

6.5.6 Additive operators
....
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.

请注意,如果允许,结果是下标差异.因此,如果指针指向相同类型的两个连续元素,则无论类型的大小如何,减法都会得到 1.(这可能就是你在具体情况下得到 1 的原因.)

Note that when allowed, the result is the subscripts difference. So if pointers point to two sequential elements of the same type, the subtraction gives 1, regardless of the size of the type. (This is perhaps the reason why you get 1 in your concrete case.)

这篇关于C中两个指针相减时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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