简体   繁体   English

从整数减去指针

[英]Subtracting pointer from an integer

    int *p = new int; 
    int a = 10; 
    cout << a+p;
    cout << a-p;

Printing a+p, p+a, pa gives an address, but ap gives me an error. 打印a + p,p + a,pa给出一个地址,但是ap给我一个错误。 Why is this so? 为什么会这样呢? Aren't pointer addresses integers? 指针不指向整数吗? And if so, shouldn't ap give me a negative value? 如果是这样,p不应给我带来负值吗?

In terms of pointer arithmetic, pointers aren't equivalent of "integer representing some address". 就指针算术而言,指针不等同于“表示某个地址的整数”。 Even addition isn't that simple: 甚至加法也不是那么简单:

  • You can't add pointer to pointer 您不能将指针添加到指针
  • Writing p+1 doesn't mean "get address value from p variable and increase it by one". p+1并不意味着“从p变量获取地址值并将其增加1”。 Actual address increment amount depends on size of pointed variable, so incrementing int64_t *p will give different result from incrementing int8_t *p 实际地址增加量取决于指针变量的大小,因此增加int64_t *p与增加int8_t *p会得到不同的结果

Why do we have such "strange behavior" for addition and subtraction of pointers? 为什么我们对于指针的加减具有这样的“奇怪行为”? Simple answer: because it's defined that way in C++ standard: 简单的答案:因为它是在C ++标准中定义的:

5.7 Additive operators 5.7加法运算符

For addition, either both operands shall have arithmetic or unscoped enumeration type, or one operand shall be a pointer to a completely-defined object type and the other shall have integral or unscoped enumeration type. 另外,两个操作数都应具有算术或无范围的枚举类型,或者一个操作数应是指向完全定义的对象类型的指针,而另一个操作数应具有整数或无范围的枚举类型。

For subtraction, one of the following shall hold: 对于减法,应满足下列条件之一:

— both operands have arithmetic or unscoped enumeration type; —两个操作数都具有算术或非范围枚举类型; or 要么

— both operands are pointers to cv-qualified or cv-unqualified versions of the same completely-defined object type; —两个操作数都是相同完全定义的对象类型的cv限定或cv非限定版本的指针; or 要么

— the left operand is a pointer to a completely-defined object type and the right operand has integral or unscoped enumeration type. —左操作数是指向完全定义的对象类型的指针,而右操作数具有整数或无作用域的枚举类型。

But there's a reason behind that restriction (which is actually describe on the same page of standard). 但是该限制背后有一个原因(实际上在标准的同一页上进行了描述)。 Pointer arithmetic is intended for the following usage: if p points to some element in array, p+1 points to the next element, p-1 points to the previous and p1-p2 shows number of elements between p1 and p2. 指针算术用于以下用途:如果p指向数组中的某个元素, p+1指向下一个元素, p-1指向前一个元素,并且p1-p2显示p1和p2之间的元素数。 In these terms p1+p2 doesn't make any sense, the same for 1-p , so they are treated as syntax errors. 在这些术语中, p1+p2没有任何意义,与1-p相同,因此将它们视为语法错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM