c - How do I find the address returned by container_of? -
i'm not looking implement function, wondering how conceptually think it. example, struct contains 5 integers. size of each integer, sizeof () 4. if address of 5th element 0x8b1000d how find address of struct? i've read address of struct address of 1st element. subtract size of each integer address of 5th in order find that?
better use offsetof macro (#include <stddef.h>
) byte offset of field in question , subtract address of field address of beginning of struct.
given address of field in structure, have subtract offset of field (produced offsetof
) address of field , gives address of structure. there's casting involved, that's it. here's example:
struct blah { int a, b, c, d, e; } xyz; int *my_blah_e = &xyz.e; struct blah *my_blah = (struct blah *) (((char *) my_blah_e) - offsetof(blah, e)); // my_blah == &xyz
Comments
Post a Comment