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

Is Obtaining the Address One Past the End of a C Array via Subscripting Legal?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-20 11:07:10915browse

Is Obtaining the Address One Past the End of a C   Array via Subscripting Legal?

Querying the Legality of One-Past-the-End Array Address Acquisition

The Question

In C , can the address of an array element one past its end be obtained through subscripting, as shown in the following code snippet?

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

Specifically, is &array[5] compliant with the C Standard?

The Answer

Yes, the code is compliant with the C Standard.

Explanation

According to the C99 draft standard:

§6.5.2.1, paragraph 2:

A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object.

§6.5.3.2, paragraph 3:

If the operand [of the & operator] 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 to the last element of an array object, the expression (P) 1 points one past the last element of the array object.

Based on these excerpts:

  • The & operator yields the address of a pointer's operand.
  • When applied to the result of a [] operator, the & operator can be removed and the [] operator becomes a operator.
  • An expression pointing to the last element of an array can legally point one past the end of the array.

Therefore, the expression &array[5] is equivalent to *(array 5), which points one past the last element of array. This is legal according to the Standard, as long as the pointer is not dereferenced.

The above is the detailed content of Is Obtaining the Address One Past the End of a C Array via Subscripting 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