Home >Backend Development >C++ >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:
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:
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!