[Solved] Why 5[a] with C arrays isn’t out of range?


To see why the note in Appendix J.2 is compatible with a[b] being the same as *(a + b), consider how an expression like a[1][7] is interpreted (assuming the declaration int a[4][5], like in the appendix):

a[1][7] is the same as *(a[1] + 7). Each element of the array a is a five-element array, so that a[1] evaluates to a pointer to the first element of a five-element array. If you add 7 to such a pointer, then the resulting pointer will point outside the five-element array, meaning you are not allowed to dereference it (standards-wise — it might work in practice). But that’s exactly what the above expression does.

The note in Appendix J.2 has nothing to do with a[5] vs. 5[a] by the way. If the array has at least six elements, then it would be reasonable to call the element “apparently accessible” in both of those expressions. They’re only trying to clarify that you’re not allowed to access a multidimensional array with overflow in any of the indices, even when it looks like it shouldn’t overflow the boundaries of the multidimensional array. It’s just a note — you can derive it independently (as above).

6

solved Why 5[a] with C arrays isn’t out of range?