简体   繁体   中英

Does offsetof require pointer derefence?

I am wondering whether a simple macro offset_of_ requires a pointer dereference of not. For example, a C++ (means that this code will be compiled using a C++ compiler) struct which is declared with packed attribute

struct A {
  int x;
  int y;
} __attribute__(packed);

Suppose that sizeof(int) == 4 in this case, to calculate the offset of y inside A , I wrote a simple macro:

#define offset_of_y (ptrdiff_t)(&(((A*)0)->y))

Can we be sure that the value of this macro is always 4 ? Is there any pointer dereference from 0 (which may be a UB) when the macro is invoked?

Many thanks for any response.

Accessing something through a null pointer is UB, period.

(Unless the context is unevaluated, but in this case it IS evaluated.)

You probably want offsetof() .


In practice your code probably could work, buf formally it's undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM