这个问题在这里已经有了答案:
Is incrementing/decrementing or adding an integer value to a pointer that is not pointing to an element in a sequence Undefined Behavior?
(2 个回答)
11 个月前关闭。
我的印象是,虽然取消引用不指向有效对象的指针是 UB,但简单地计算此类指针就可以了。
但是,如果我理解 expr.add[4]正确,事实并非如此。
那么这些指针计算中哪些是明确定义的?
int a = 42;
int *p = &a;
p; // valid, and obviously ok
p++; // invalid, but ok, because one past the end of 'array' containing 1 element?
p++; // UB ?
这个案子怎么样?
int *p = nullptr;
p; // invalid, and obviously ok (considered one past the end?)
p++; // one past the end? or UB?
最佳答案
在您的第一个示例中,第一个 p++
是明确定义的,因为非数组被认为是一个长度的数组。
这是相关报价( basic.compound/3.4 ):
For purposes of pointer arithmetic ([expr.add]) and comparison ([expr.rel], [expr.eq]), a pointer past the end of the last element of an array x of n elements is considered to be equivalent to a pointer to a hypothetical array element n of x and an object of type T that is not an array element is considered to belong to an array with one element of type T.
后
p++
, p
它将指向(假设)数组的最后一个(也是唯一一个)元素,这是明确定义的。它不是“无效,但可以”,因为指向对象末尾的指针不是无效指针,basic.compound/3.2 :Every value of pointer type is one of the following:
[...]
a pointer past the end of an object
[...]
an invalid pointer value.
第二个
p++
第一个例子的 UB 是 UB,因为结果将指向未定义的假设 (&a)[1] 元素。在你的第二个例子中,
p++
是 UB,因为只有 0 可以添加到 nullptr
( expr.add/4.1 ):
If P evaluates to a null pointer value and J evaluates to 0, the result is a null pointer value.
[...]
Otherwise, the behavior is undefined.
关于c++ - 哪些指针值可以很好地计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61296481/