Alex Rivera | Logout

How do you use offsetof() on a struct?

Asked 2011-08-24T18:17:19.330
12

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

1 Answer

-2

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 trying

offsetof(struct mystruct1, u_line.line) 

This 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.

answered 2011-08-24T18:26:29.050

Your Answer