Home >Backend Development >C++ >Is Taking the Address One Past the End of a C Array Legal?

Is Taking the Address One Past the End of a C Array Legal?

Susan Sarandon
Susan SarandonOriginal
2024-12-26 07:18:45404browse

Is Taking the Address One Past the End of a C   Array Legal?

Is Taking the Address of an Array Element One Past the End Allowed by the C Standard?

The code snippet below has raised discussions about its validity according to the C Standard:

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

Specifically, is &array[5] a legal C expression in this context?

Legality According to the C Standard

C Standard defines the legality of this expression:

  • C 17 Standard 6.5.2.1, Paragraph 2: Defines E1[E2] as identical to (*((E1) (E2))).
  • C 17 Standard 6.5.3.2, Paragraph 3: States that for a [] expression, the & operator and the implied * are not evaluated, resulting in &(E1 E2).
  • C 17 Standard 6.5.6, Paragraph 8: Allows pointers to point one element past the end of an array, but prohibits dereferencing them.

Interpretation

By applying these rules to &array[5], we have:

&array[5] = &*(array + 5) = (array + 5)

Since (array 5) points one past the end of the array and is not dereferenced, it is a legal expression according to the C Standard.

Comparison with the C Standard

This behavior is also consistent with the C Standard, which allows taking the address of elements beyond the end of an array, again provided that they are not dereferenced.

Reason for Different Treatment

The decision to treat array 5 and &array[4] 1 differently is rooted in the differing purposes of these expressions:

  • array 5 provides a pointer one past the end of the array, allowing for comparisons and traversing beyond the array's bounds.
  • &array[4] 1 attempts to create a reference to a nonexistent element, which would lead to undefined behavior.

The above is the detailed content of Is Taking the Address One Past the End of a C Array Legal?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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