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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With