How is container_of utilized?
“container_of is a C language macro used to obtain a pointer to the structure containing a specific member by using a pointer to that member.”
Here is how to use it:
#define container_of(ptr, type, member) \
((type *)((char *)(ptr) - offsetof(type, member)))
Explanation of parameters:
- ptr: pointer to a member of a structure.
- type: the type of the structure.
- Member: The name of a member within a structure.
The container_of macro calculates the offset of a member within a structure using the offsetof macro, then subtracts the offset from the member pointer to obtain a pointer to the structure.
Here is an example of using the container_of macro:
#include <stddef.h>
struct Person {
char name[20];
int age;
};
int main() {
struct Person p = {"John Doe", 25};
int *p_age = &p.age;
struct Person *p_ptr = container_of(p_age, struct Person, age);
printf("Name: %s\n", p_ptr->name);
printf("Age: %d\n", p_ptr->age);
return 0;
}
Output result:
Name: John Doe
Age: 25
In the example above, using the container_of macro, we can obtain a pointer to the struct Person containing the member p.age by accessing p_ptr through the pointer p_age, allowing us to access other members of the struct.