Home >Backend Development >C++ >Is it Legal in C to Take the Address of an Array Element One Past the End?

Is it Legal in C to Take the Address of an Array Element One Past the End?

Linda Hamilton
Linda HamiltonOriginal
2024-12-18 01:40:10467browse

Is it Legal in C   to Take the Address of an Array Element One Past the End?

Can You Take the Address of an Array Element One Past the End?

The following code has been the subject of debate in the programming community:

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

Specifically, the question of whether &array[5] is legal C code in this context has been raised.

The C Standard's Stance

According to the C Standard, specifically:

  • §6.5.2.1: A subscripted designation (E1[E2]) is equivalent to *((E1) (E2)).
  • §6.5.3.2: When you take the address of an expression resulting from a [] operator, it is equivalent to replacing the [] with .

Implications for &array[5]

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

  • &array[5] is equivalent to &array[0] 5.
  • &array[0] 5 points one element past the end of array.

Is It Legal?

Yes, it is legal. The standard explicitly permits pointers to point one element past the end of an array, provided they are not dereferenced. In this case, &array[5] is only used to obtain an address, not to access the value at that address, so it is within the bounds of what the standard allows.

Why the Difference from array 5 or &array[4] 1?

The behavior of &array[5] differs from array 5 or &array[4] 1 due to the precedence of the and [] operators combined with the behavior of the unary * operator implied by []. Specifically:

  • array 5 is evaluated as *(array 5), which attempts to dereference a pointer pointing one past the end of array, which is undefined behavior.
  • &array[4] 1 is evaluated as &*(array 4) 1, which is equivalent to array 5, and therefore also attempts to dereference a pointer pointing one past the end of array.

In contrast, &array[5] is evaluated as if the & operator were removed and the [] operator were changed to a operator, resulting in array 5, but without the evaluation of the unary * operator.

The above is the detailed content of Is it Legal in C to Take the Address of an Array Element One Past the End?. 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