Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

increment of pointer to array

I'm trying to understand why the following C++ code does not compile

int main () {
  int a[10];
  int (*p)[10] = &a;
  int *q = static_cast<int *>(++p);
}

If it's not obvious, what I was trying to do is find a pointer to the end of the array by using pointer arithmetic.

My understanding so far is that p has type pointer to array of ten ints and so does the expression ++p. Normally, I can assign an array of ints to a variable of type pointer to int but this fails on the incremented pointer ++p.

I first tried without the static_cast but that didn't work either.

like image 562
Sidious Lord Avatar asked Mar 10 '23 00:03

Sidious Lord


1 Answers

p has type pointer to array of ten ints

This is correct.

Normally, I can assign an array of ints to a variable of type pointer to int

This is also correct. Except, if you compare your two statements, you should see the obvious difference: p is not an array of ints, it is a pointer to an array of ints. Hence, the difference.

Now, if you dereference that pointer to an array, your result will be an expression whose type is an array (loosely speaking), and that can be decayed to a pointer:

int *q = static_cast<int *>(*++p);
like image 55
Sam Varshavchik Avatar answered Mar 20 '23 20:03

Sam Varshavchik