Home > Backend Development > C++ > body text

Is Pointer Arithmetic on Non-Character Arrays in C Defined Behavior?

Linda Hamilton
Release: 2024-11-09 09:59:02
Original
903 people have browsed it

Is Pointer Arithmetic on Non-Character Arrays in C   Defined Behavior?

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

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!

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