Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
575 views
in Technique[技术] by (71.8m points)

c - How do you use offsetof() on a struct?

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;
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The offsetof() macro takes two arguments. The C99 standard says (in §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.

So, you need to write:

offsetof(struct mystruct1, u_line.line);

However, we can observe that the answer will be zero since mystruct1 contains a union as the first member (and only), and the line part of it is one element of the union, so it will be at offset 0.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...