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:
Implications for &array[5]
Applying these rules to &array[5], we have:
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:
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!