变量不在数组中的指针算术

Pointer arithmetic with variables not in an array

我有以下问题;如果 a 是一个包含 10 个元素的 int 数组,我可以定义指针

int*b=&a[3]; 
int*c=&[2];

然后我可以对这些指针进行算术运算,例如 int d=a-c; 这将 return 数组中 b 和 c 之间的 int 值的数量。所以我的问题是我是否也被允许对任何可能不在数组中的变量进行这样的指针算术运算。例如:

int a=10; 
int b=20; 
int*c=&a; 
int* d=&b;

然后执行 int e=d-c;int*e=c+1;

我问的原因是我收到了关于这是否会导致未定义行为的相互矛盾的信息,

[expr.add]标准草案:

  1. When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the expression P points to element x[i] of an array object x with n elements,86 the expressions P + J and J + P (where J has the value j) point to the (possibly-hypothetical) element x[i + j] if 0 ≤ i + j ≤ n; otherwise, the behavior is undefined. Likewise, the expression P - J points to the (possibly-hypothetical) element x[i − j] if 0 ≤ i − j ≤ n; otherwise, the behavior is undefined.

  2. When two pointers to elements of the same array object are subtracted, the type of the result is an implementation-defined signed integral type; this type shall be the same type that is defined as std::ptrdiff_- t in the header (21.2). If the expressions P and Q point to, respectively, elements x[i] and x[j] of the same array object x, the expression P - Q has the value i − j; otherwise, the behavior is undefined. [ Note: If the value i − j is not in the range of representable values of type std::ptrdiff_t, the behavior is undefined. — end note ]


86) An object that is not an array element is considered to belong to a single-element array for this purpose; see 8.3.1. A pointer past the last element of an array x of n elements is considered to be equivalent to a pointer to a hypothetical element x[n] for this purpose; see 6.9.2.


c+1 定义明确,因为它将指向变量被视为用于引用规则目的的 "single-element array",因此满足 0 ≤ 0 + 1 ≤ 1。但是间接指向该指针的定义并不明确,因为它超过了 "array".

的末尾

d-c 有未定义的行为。