I know it would be very bad coding-style, but the following code runs perfectly on my machine. But is the behavior well defined? Portable?
int *p = new int;
int *q = &p;
q[-1] = 41;
std::cout << p;
This is well defined, both syntactically and semantically.
E1[E2]is identical (by definition) to
So your expression is the same as
*(q-1) = 41;, so is syntactically valid.
When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integral expression.
q points to an element of an array object of a valid size for your integral expression, it is semantically valid.