Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use offsetof() on a struct?

Tags:

c

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;
};
like image 851
ken Avatar asked Aug 24 '11 18:08

ken


People also ask

How does offsetof work in C?

The offsetof() macro is an ANSI -required macro that should be found in stddef. h. Simply put, the offsetof() macro returns the number of bytes of offset before a particular element of a struct or union.

What is offsetof C++?

The offsetof macro returns the offset in bytes of memberName from the beginning of the structure specified by structName as a value of type size_t . You can specify types with the struct keyword. Note. offsetof is not a function and cannot be described using a C prototype.

How do you find the offset of a structure member?

Use offsetof() to find the offset from the start of z or from the start of x . #include <stddef. h> size_t offsetof(type, member); offsetof() returns the offset of the field member from the start of the structure type.

Where is offsetof defined?

Defined in header <cstddef> #define offsetof(type, member) /*implementation-defined*/ The macro offsetof expands to an integral constant expression of type std::size_t, the value of which is the offset, in bytes, from the beginning of an object of specified type to its specified subobject, including padding if any.


2 Answers

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.

like image 195
Jonathan Leffler Avatar answered Nov 15 '22 13:11

Jonathan Leffler


A great article to read on this is:

Learn a new trick with the offsetof() macro

I use the offsetof macro frequently in my embedded code, together with the modified SIZEOF macro as discussed in the article.

like image 23
ACRL Avatar answered Nov 15 '22 14:11

ACRL