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:
- DATA TYPE: Structure Type.
- 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:
- The return type of the offsetof macro is size_t, representing the number of bytes of an offset.
- When calling the offsetof macro, the structure type passed in must be a defined type.
- When using the offsetof macro, the member name passed in must be an actual member name that exists in the structure.
- 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.