Is it valid to address one element beyond the end of an array?


It's valid to address it, but not to see what's there. (The really short answer is, "Yes, so don't worry about it.") With most compilers, if you say

int i, a[MAX], j;

then either i or j is at the part of memory just after the last element of the array. The way to see whether i or j follows the array is to compare their addresses with that of the element following the array. The way to say this in C is that either

& i == & a[ MAX ]

is true or

& a[ MAX ] == & j

is true. This isn't guaranteed; it's just the way it usually works. The point is, if you store something in a[MAX], you'll usually clobber something outside the a array. Even looking at the value of a[MAX] is technically against the rules, although it's not usually a problem. Why would you ever want to say &a[MAX]? There's a common idiom of going through every member of a loop using a pointer. Instead of

for ( i = 0; i < MAX; ++i )
        /* do something */;

C programmers often write this:

for ( p = a; p < & a[ MAX ]; ++p )
        /* do something */;

The kind of loop shown here is so common in existing C code that the C standard says it must work.


© 2017