根据结构体变量成员的指针获取整个结构体的指针
#include <stdio.h> 2 #include "stdlib.h"
#include "string.h"#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#define container_of(ptr, type, member) ({ \const typeof( ((type *)0)->member ) *__mptr = (ptr); \(type *)( (char *)__mptr - offsetof(type,member) );})struct person {char name[10];int age;int height;int weight;
};void show_person(struct person *per)
{printf("name = %s\n", per->name);printf("age = %d\n", per->age);printf("height = %d\n", per->height);printf("weight = %d\n", per->weight);
}int get_addr(char *name)
{struct person *per;printf("name = %p\n", name);per = container_of(name, struct person, name);printf("per = %p\n", per);show_person(per);return 0;
}int main()
{struct person *per = NULL;per = (struct person*)malloc(sizeof(struct person));printf("per = %p\n", per);strcpy(per->name, "wang");per->age = 18;per->height = 168;per->weight = 120;printf("test\n");get_addr(per->name);return 0;
}
container_of 可以根据结构体成员的地址找到整个结构体的地址,但是前提是结构体的空间要是连续的