What is the usage of offsetof in Linux?

In Linux, offsetof is a macro used to retrieve the offset of a member in a structure.

The specific usage is as follows:

#include <stddef.h>

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

Parameter Description:

  1. DATA TYPE: Structure Type.
  2. MEMBER: Member within a struct.

When using, you can obtain the offset of a member in a structure by calling this macro, as shown below:

#include <stddef.h>
#include <stdio.h>

struct example {
    int a;
    char b;
    float c;
};

int main() {
    size_t offset = offsetof(struct example, b);
    printf("Offset of member 'b' in struct example: %zu\n", offset);
    return 0;
}

Output of the program:

Offset of member 'b' in struct example: 4

Things to note:

  1. The return type of the offsetof macro is size_t, representing the number of bytes of an offset.
  2. When calling the offsetof macro, the structure type passed in must be a defined type.
  3. When using the offsetof macro, the member name passed in must be an actual member name that exists in the structure.
  4. The implementation of the offsetof macro calculates the offset by converting a pointer to a structure type to a zero pointer, and then taking the address of the member. This method exploits the fact that in C language, the addresses of structure members are stored consecutively.
Leave a Reply 0

Your email address will not be published. Required fields are marked *