gpt4 book ai didi

c - 如何在结构上使用 offsetof()?

转载 作者:太空狗 更新时间:2023-10-29 17:20:54 24 4
gpt4 key购买 nike

我想要 mystruct1 中的 offsetof() 参数行。我试过了

offsetof(struct mystruct1, rec.structPtr1.u_line.line) 

还有

offsetof(struct mystruct1, line)  

但两者都不起作用。

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;
};

最佳答案

offsetof()宏有两个参数。 C99 标准说(在 §7.17 <stddef.h> ):

offsetof(type, member-designator)

which expands to an integer constant expression that has type size_t, the value of which is the offset in bytes, to the structure member (designated by member-designator), from the beginning of its structure (designated by type). The type and member designator shall be such that given

static type t;

then the expression &(t.member-designator) evaluates to an address constant.

所以,你需要写:

offsetof(struct mystruct1, u_line.line);

但是,我们可以观察到答案将为零,因为 mystruct1包含 union作为第一个成员(也是唯一一个),以及 line它的一部分是并集的一个元素,因此它将位于偏移量 0 处。

关于c - 如何在结构上使用 offsetof()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7180290/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com