Access element beyond the end of an array in C


I've been reading K & R's book on C, and found that pointer arithmetic in C allows access to one element beyond the end of an array. I know C allows to do almost anything with memory but I just don't understand, what is the purpose of this peculiarity?

Best Solution

C doesn't allow access to memory beyond the end of the array. It does, however, allow a pointer to point at one element beyond the end of the array. The distinction is important.

Thus, this is OK:

char array[N];
char *p;
char *end;

for (p = array, end = array + N; p < end; ++p)

(Doing *end would be an error.)

And that shows the reason why this feature is useful: a pointer pointing at the (non-existent) element after the end of the array is useful for comparisons, such as in loops.

Technically speaking, that is everything the C standard allows. However, in practice, the C implementation (compiler and runtime) does not check whether you access memory beyond the end of the array, whether it is one element or more. There would have to be bounds checking and that would slow down program execution. The kinds of programs C is best suited for (systems programming, general purpose libraries) tend to benefit more from the speed than the security and safety bounds checking would give.

That means C is perhaps not a good tool for general purpose application programming.