Are negative array indexes allowed in C?
That is correct. From C99 §6.5.2.1/2:
The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))).
There's no magic. It's a 1-1 equivalence. As always when dereferencing a pointer (*), you need to be sure it's pointing to a valid address.
Sounds fine to me. It would be a rare case that you would legitimately need it however.
This is only valid if arr
is a pointer that points to the second element in an array or a later element. Otherwise, it is not valid, because you would be accessing memory outside the bounds of the array. So, for example, this would be wrong:
int arr[10];
int x = arr[-2]; // invalid; out of range
But this would be okay:
int arr[10];
int* p = &arr[2];
int x = p[-2]; // valid: accesses arr[0]
It is, however, unusual to use a negative subscript.