Pointer Arithmetic on Non-Character Arrays
In C , the behavior of pointer arithmetic is well-defined for pointers that reference arrays or point to the start of an array. However, questions arise when pointer arithmetic is applied to pointers that don't directly point to character arrays.
Consider the following code snippet:
struct Foo { float x, y, z; }; Foo f; char *p = reinterpret_cast<char *>(&f) + offsetof(Foo, z);
The problematic line marked with (*) assigns the address of the z member of the Foo struct to the p pointer. According to the standard (expr.add/4), this operation could be considered undefined behavior (UB) since p does not point to a char array.
However, the standard also states that the underlying bytes of any trivially copyable object can be copied into an array of char or unsigned char. This implies that pointer arithmetic should be valid for pointers to the raw bytes that make up an object, regardless of whether they form an array.
In this specific case, the intent behind the code is to access the z member using reinterpret_cast. Although the standard does not explicitly state that pointer arithmetic is defined in such scenarios, it would greatly limit the usefulness of offsetof if it were not.
Therefore, the addition in line (*) is considered valid in C . The pointer arithmetic on p is allowed, and it correctly points to the z member within the Foo struct.
The above is the detailed content of Is Pointer Arithmetic on Non-Character Arrays in C Defined Behavior?. For more information, please follow other related articles on the PHP Chinese website!