#define element_to_entity(p,T,e) ((T*)((unsigned char *)(p) - ((unsigned char *)(&(((T *)0)->e)))))
很多人会对((T *)0)很迷糊,其实换个((T *)p) 形式或许更好理解,如果当p的地址为0时就成了((T *)0)
例子
#include <stdio.h>
struct any_data
{
int a;
int b;
list_t list;
};
#define element_to_entity(p,T,e) ((T*)((unsigned char *)(p) - ((unsigned char *)(&(((T *)0)->e)))))
int main()
{
struct any_data s;
int *p = &s.list;
struct any_data *ps = element_to_entity(p, struct any_data, list);
printf("s: %p, ps:%p/n", &s, ps);
return 0;
}