C++

Topic: Array

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 sayint 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 ] == & jis 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 offor ( 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.

Browse random answers: