Is Pointer Addition Undefined When Not Pointing to a Char Array?
The C 17 standard states that adding integral values to pointers results in a pointer of the same type as the operand, and the result points to a (hypothetical) element within an array if the operation stays within its bounds. However, it remains unclear whether this applies to pointers that do not point to char arrays.
Consider the following code:
struct Foo { float x, y, z; }; Foo f; char *p = reinterpret_cast<char *>(&f) + offsetof(Foo, z); // (*) *reinterpret_cast<float *>(p) = 42.0f;
Does the line marked with (*) constitute undefined behavior (UB)? The pointer p points to a float, not a character array. According to the cited paragraph, this should result in UB. However, if it were UB, it would significantly limit the usefulness of offsetof().
The standard's definition of trivially copyable types states that their underlying bytes can be copied into a char array using functions like std::memcpy. This implies that addition should be defined for pointers to the raw bytes that make up an object, regardless of whether the result will be used to copy bytes into an array.
Whether this implies the involved bytes already form an array or constitute a special exception to the usual rules for the operator is unclear. However, either interpretation would render the addition in the code valid. Thus, it can be concluded that adding to a char * pointer does not necessarily result in UB, even if it does not point to a char array.
The above is the detailed content of Is Pointer Addition Undefined When Not Pointing to a Character Array in C 17?. For more information, please follow other related articles on the PHP Chinese website!