Pointer Arithmetic on pointers to pointers and the like
Is to well defined to use pointer arithm开发者_Go百科etic 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)
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:
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. 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.
Of course!
p + n
where p
is a pointer and n
is an integer is always well-defined. It produces the address which is "n times the size of the element type p points to" bytes from p
itself. In this case p2
is a pointer to a pointer. So p2 + 4
is the address "4 * the-size-of-pointers" bytes past p2
.
Since you are pointing to local variables in your specific example, it would be odd. But it will not be illegal.
精彩评论