Why is it pointing to the one before the first element of the array that is not allowed in C?

In C, a pointer is allowed to point to any element of the array, as well as to the last one element of the array; indicating that this behavior is undefined (C11 standard, §6.5.6, clause 8).

However, why point to one before the first element of the array is not resolved in the same way?

PS: I know that in order to circumvent the aforementioned restriction, it is sometimes possible to declare an array of 1 unit larger than necessary, then use only positions from 1 to store items and, finally, leave position 0 as a guarantee that moving the array back will be safe . However, sometimes we need to use a given array, and then the problem of pointing to one before the first element remains.

+4
source share
3 answers

The topic "pointer allows you to point to any element of the array" has been part of the C language for a very long time; it can already be found in ANSI-C standard / C89 (see section 6.3.6 Additive operators, page 46f), which already mentions that arithmetic overflows should be prevented in this implementation range. In this case, at the end of page 47 you can also find a footnote that explains the rational behind it:

- () : , , , , . .

( ) , " ", .

, , ( , , ).

- ( ), , " " . , "" ( ) " , , " " " - , .

+3

, ,

  • (- )
  • , X , X,
  • (- ).

.

+3

The rationale for why it is primarily permitted to specify one after the array is to enable certain types of C ++ / STL-ish programming:

int array [n] = ...;
int* begin = array;
int* end = array + n;

for(int* i=begin; i!=end; i++)
...

For situations like the above, it makes sense to specify one element after the array. But, of course, it makes no sense to actually access this element, which would be undefined.

Thus, the foregoing is a special case. However, there is no situation where it makes sense to specify one element in front of the array.

+2
source

Source: https://habr.com/ru/post/1685606/


All Articles