Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 340
zuselegacy Avatar asked Jun 08 '26 16:06

zuselegacy


2 Answers

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.

like image 102
curiousguy Avatar answered Jun 11 '26 23:06

curiousguy


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.

like image 30
Ray Toal Avatar answered Jun 11 '26 23:06

Ray Toal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!