Home > Backend Development > C++ > Is `&array[5]` a Valid Pointer in C Beyond Array Bounds?

Is `&array[5]` a Valid Pointer in C Beyond Array Bounds?

Mary-Kate Olsen
Release: 2025-01-04 10:03:35
Original
362 people have browsed it

Is `&array[5]` a Valid Pointer in C   Beyond Array Bounds?

Can Array Subscripting Point Beyond Array Bounds?

The question arises whether the following code is compliant with the C Standard:

int array[5];
int *array_begin = &array[0];
int *array_end = &array[5];
Copy after login

Specifically, the validity of &array[5] in this context is under scrutiny.

C Standard

According to the C99 draft standard:

  • §6.5.2.1, Paragraph 2: "E1[E2] is identical to (*((E1) (E2)))"
  • §6.5.3.2, Paragraph 3 (Emphasized): "If the operand is the result of a [] operator, neither the & operator nor the unary * that is implied by the [] is evaluated and the result is as if the & operator were removed and the [] operator were changed to a operator."
  • §6.5.6, Paragraph 8: "If the expression P points one past the last element of an array object, the expression (P) 1 points one past the last element of the array object, and if the expression Q points one past the last element of an array object, the expression (Q) - 1 points to the last element of the array object."

Conclusion

These provisions indicate that:

  • Pointers can legitimately point one element past the end of an array (without being dereferenced).
  • &array[5] is equivalent to &*(array 5), which in turn is equivalent to (array 5).
  • (array 5) points one past the end of the array.
  • Since &array[5] does not result in a dereference, it is legal according to the C Standard.

The above is the detailed content of Is `&array[5]` a Valid Pointer in C Beyond Array Bounds?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template