Thursday, December 16, 2010

find structure pointer when you have its one field pointer

you may know it but worth recalling it.

struct my_type {
int x;
char a[20];
char b[20];
int y;
int z;
};
struct my_type *ptr;

suppose you know &(ptr->y) in your function, then can we find out the ptr value? In other words, we have a pointer of a field (say y) of the any structure. We want to find out the pointer of the structure which contain this field. We know the type of the structure (struct my_type) and the field name (y) whose pointer is given.

The trick is to find the offset of the y by referencing the same structure type at address 0. and then deduct this offset from the given address of y and you will get the container structure pointer. Linux kernel uses this technique extensively by container_of macro.

offset_of_y = (int) &((struct my_type *) 0)->y;
ptr = (struct my_type *)((char *)y_ptr - offset_of_y);

Download the sample C program demonstrating it.

No comments:

Post a Comment