Home > Backend Development > C++ > Is Pointer Addition Undefined When Not Pointing to a Character Array in C 17?

Is Pointer Addition Undefined When Not Pointing to a Character Array in C 17?

Linda Hamilton
Release: 2024-11-11 11:48:03
Original
525 people have browsed it

Is Pointer Addition Undefined When Not Pointing to a Character Array in C  17?

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;
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template