如何在结构上使用 offsetof() ?
我想要 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;
};
I want the offsetof() the param line in mystruct1
. I've tried
offsetof(struct mystruct1, rec.structPtr1.u_line.line)
and also
offsetof(struct mystruct1, line)
but neither works.
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;
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
offsetof()
宏有两个参数。 C99 标准规定(在 §7.17
中):因此,您需要这样写:
但是,我们可以观察到答案将为零,因为
mystruct1
包含一个union
作为第一个成员(也是唯一的成员),并且它的 >line
部分是联合的一个元素,因此它将位于偏移量 0 处。The
offsetof()
macro takes two arguments. The C99 standard says (in §7.17<stddef.h>
):So, you need to write:
However, we can observe that the answer will be zero since
mystruct1
contains aunion
as the first member (and only), and theline
part of it is one element of the union, so it will be at offset 0.您的
struct mystruct1
有 1 个名为u_line
的成员。 您可以看到该成员或该成员的偏移量如果您指定每个“亲子关系级别”,
Your
struct mystruct1
has 1 member namedu_line
. You can see the offset of that memberor of members down the line if you specify each "level of parenthood"
首先,据我所知,
offsetof
旨在仅与结构的直接成员一起使用(我的说法正确吗?)。其次,了解流行
offsetof
实现的内部细节,我可以建议尝试这应该可行。它是否符合标准对我来说是一个悬而未决的问题。
PS 从@Jonathan Leffler 的回答来看,这实际上应该有效。
Firstly, AFAIK,
offsetof
is intended to be used with immediate members of the struct only (am I right on this?).Secondly, knowing the internal details of popular
offsetof
implementations I can suggest tryingThis should work. Whether it is standard-compliant is an open question for me.
P.S. Judging by @Jonathan Leffler's answer, this should actually work.