Home >Backend Development >C++ >Is Pointer Arithmetic on Non-Array Data Structures Defined or Undefined Behavior in C ?
Is Pointer Arithmetic on Non-Array Data Structures Undefined Behavior?
The question arises from the apparent conflict between the C 17 standard regarding pointer addition and the functionality of the offsetof macro. According to the cited paragraph, adding to a "char " pointer should result in undefined behavior if it doesn't point to a char array. However, the code example provided involves adding to a "char " pointer obtained from reinterpret_casting the address of a "Foo" struct. This doesn't seem to follow the rule, as the pointer doesn't point to a char array.
However, upon further examination of the standard, we find guidance in section 3.9.2: "For any object (other than a base-class subobject) of trivially copyable type T, whether or not the object holds a valid value of type T, the underlying bytes making up the object can be copied into an array of char or unsigned char."
This statement suggests that the standard considers the underlying bytes of any object as copyable, regardless of whether they represent an array. This implies that the addition you're performing in your code should be valid, even though the pointer isn't pointing to an array. The addition is defined on the raw bytes, and the resulting value is used to access the desired float member of the "Foo" struct.
Thus, the addition operation in the provided code example is not undefined behavior. It allows you to access and modify the bytes representing the struct's member using reinterpret_casting and offsetof.
The above is the detailed content of Is Pointer Arithmetic on Non-Array Data Structures Defined or Undefined Behavior in C ?. For more information, please follow other related articles on the PHP Chinese website!