指针加法与减法 [英] Pointer addition vs subtraction

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

问题描述

$ 5.7-

"[..]此外,两个操作数都应具有算术或枚举类型,或者一个操作数应是指向完全定义的对象类型的指针,而另一个操作数应具有整数或枚举类型.

"[..]For addition, either both operands shall have arithmetic or enumeration type, or one operand shall be a pointer to a completely defined object type and the other shall have integral or enumeration type.

2对于减法,应满足下列条件之一:—两个操作数都具有算术或枚举类型;或者—两个操作数都是相同完全定义的对象类型的cv限定或cv非限定版本的指针;或者—左操作数是指向完全定义的对象类型的指针,而右操作数具有整数或枚举类型.

2 For subtraction, one of the following shall hold: — both operands have arithmetic or enumeration type; or — both operands are pointers to cv-qualified or cv-unqualified versions of the same completely defined object type; or — the left operand is a pointer to a completely defined object type and the right operand has integral or enumeration type.

int main(){
        int buf[10];
        int *p1 = &buf[0];
        int *p2 = 0;

        p1 + p2;       // Error

        p1 - p2;       // OK
}

所以,我的问题是为什么在C ++中不支持指针加法",但是支持指针减法"?

So, my question is why 'pointer addition' is not supported in C++ but 'pointer subtraction' is?

推荐答案

两个指针之间的差异意味着可以在两个指针的目标之间容纳的类型的元素数量.两个指针的总和表示……没有……什么,这就是为什么不支持它的原因.

The difference between two pointers means the number of elements of the type that would fit between the targets of the two pointers. The sum of two pointers means...er...nothing, which is why it isn't supported.

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

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