Originally Posted by
cdalten
Why does C allow a pointer to advance just one beyond the end of the array
I think it is to allow this idiom.
Code:
#include <stdio.h>
int main(void)
{
int *ptr, array[] = {1,2,3,4,5};
size_t i;
for ( i = 0; i < sizeof array / sizeof *array; ++i )
{
printf("array[%lu] = %d\n", (long unsigned)i, array[i]);
}
for ( ptr = array; ptr < array + sizeof array / sizeof *array; ++ptr )
{
printf("*ptr = %d\n", *ptr);
}
/* rather than requiring */
for ( ptr = array; ptr <= array + sizeof array / sizeof *array - 1; ++ptr )
{
printf("*ptr = %d\n", *ptr);
}
return 0;
}
The expression array + sizeof array / sizeof *array is one element beyond the array bounds.