从整数中减去指针

Subtracting pointer from an integer

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

打印a+p,p+a,p-a给地址,a-p给我报错。为什么会这样?指针地址不是整数吗?如果是这样,a-p 不应该给我一个负值吗?

在指针运算方面,指针不等同于 "integer representing some address"。即使加法也不是那么简单:

  • 您不能将指针添加到指针
  • p+1并不代表"get address value from p variable and increase it by one"。实际地址增量取决于指向变量的大小,因此递增 int64_t *p 将给出与递增 int8_t *p
  • 不同的结果

为什么我们有这样的"strange behavior"来做指针的加减法呢?简单回答:因为它在 C++ 标准中是这样定义的:

5.7 Additive operators

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; or

— the left operand is a pointer to a completely-defined object type and the right operand has integral or unscoped enumeration type.

但是这个限制背后是有原因的(实际上在标准的同一页上有描述)。指针算法用于以下用法:如果 p 指向数组中的某个元素,p+1 指向下一个元素,p-1 指向前一个元素, p1-p2 显示数字p1 和 p2 之间的元素。在这些术语中 p1+p2 没有任何意义,对于 1-p 也是如此,因此它们被视为语法错误。