[英]Pointer Arithmetic on pointers to pointers and the like
Is to well defined to use pointer arithmetic on pointers to pointers? 是否明确定义在指针指针上使用指针算法? eg 例如
int a=some_value;
int* p=&a;
int**p2=&p;
Now would it be well defined behavior to perform arithmetic on p2?(eg p2+1, p2+2,etc) 现在,对p2执行算术会有明确定义的行为吗?(例如p2 + 1,p2 + 2等)
The other answer is completely wrong: 另一个答案是完全错误的:
int *p = &a;
declares a single pointer variable (not a array of pointers). 声明了一个指针变量(未指针的数组)。 This is equivalent, WRT indexing, with an array with a single element: 这与WRT索引等效,带有单个元素的数组:
int *(array[1]) = { &a };
so you can do (&array[0]) + 1
or array + 1
, or p + 1
, because forming a one-past-the-end pointer is allowed: a one-past-the-end pointer points to an imaginary element that's just after the end of the array. 所以你可以做(&array[0]) + 1
或array + 1
,或p + 1
,因为允许形成一个一个接一个的结束指针:一个过去的指针指向一个虚构的元素就在阵列结束之后。 The one-past-the-end pointer is not dereferenceable, because it points to no real object. 一个接一个结束的指针不可解除引用,因为它指向没有真实对象。
But you cannot compute any other pointer value . 但是你无法计算任何其他指针值 。
In particular, p+2
is not valid. 特别是, p+2
是无效的。
Of course! 当然!
p + n
where p
is a pointer and n
is an integer is always well-defined. 其中p
是指针, n
是整数,总是定义良好。 It produces the address which is "n times the size of the element type p points to" bytes from p
itself. 它产生的地址是“p元素类型大小的n倍”,指向p
本身的字节。 In this case p2
is a pointer to a pointer. 在这种情况下, p2
是指向指针的指针。 So p2 + 4
is the address "4 * the-size-of-pointers" bytes past p2
. 所以p2 + 4
的地址是“4 *的大小-的指针”字节过去p2
。
Since you are pointing to local variables in your specific example, it would be odd. 由于您在特定示例中指向局部变量,因此它会很奇怪。 But it will not be illegal. 但这不是违法的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.