4

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.

5
  • You could make p an int*: int* p = a; int* q = ++p; Commented Jan 28, 2017 at 18:41
  • @GregKikola Yes, I could do that, but that's not what I want to do. I think the pointer arithmetic should be different in the two cases. Commented Jan 28, 2017 at 18:47
  • 2
    Oh, I misinterpreted, I didn't see the note about wanting q to point to the end of the array. In that case you could do int *q = a + 10;. Alternatively, with C++11, int* q = std::end(a); (just include <iterator>). Commented Jan 28, 2017 at 19:02
  • Even if you get this to work, the next person to look at this code will likely not understand it. I think (a+10) is much clearer. Commented Jan 28, 2017 at 19:15
  • @brianbeuning I'm not planning to use this in production code. I was just playing with pointers... Commented Jan 28, 2017 at 19:20

1 Answer 1

7

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, that makes sense.
The weird thing is that if I print p and q I get the same thing. So there seems to be something weird about pointer arithmetic on pointers to arrays.
@SidiousLord p and q are different types, but they hold the same address, both pointing to the element just after the end of the array. p points to an array of 10 ints starting at that address, q points to an int at that same address.
@GregKikola I thing I found my error. To get what I wanted I need to use *p++ not *++p. Then p will point at the beginning of the array while q points to the end of the array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.