我想要offsetof()参数行mystruct1.我试过了
offsetof(struct mystruct1, rec.structPtr1.u_line.line)
Run Code Online (Sandbox Code Playgroud)
并且
offsetof(struct mystruct1, line)
Run Code Online (Sandbox Code Playgroud)
但都不起作用.
union {
struct mystruct1 structPtr1;
struct mystruct2 structPtr2;
} rec;
typedef struct mystruct1 {
union {
struct {
short len;
char buf[2];
} line;
struct {
short len;
} logo;
} u_line;
};
Run Code Online (Sandbox Code Playgroud)
该offsetof()宏有两个参数.C99标准说(§7.17 <stddef.h>):
Run Code Online (Sandbox Code Playgroud)offsetof(type, member-designator)它
size_t从结构的开头(由类型指定)扩展为一个整数常量表达式,该表达式的类型(其值是以字节为单位的偏移量)到结构成员(由member-designator指定).类型和成员指示符应为给定的Run Code Online (Sandbox Code Playgroud)static type t;然后表达式
&(t.member-designator)求值为地址常量.
所以,你需要写:
offsetof(struct mystruct1, u_line.line);
Run Code Online (Sandbox Code Playgroud)
但是,我们可以观察到答案将为零,因为mystruct1包含a union作为第一个成员(并且仅),并且line它的一部分是union的一个元素,因此它将在偏移0处.