如果成员名是一个指针该怎么办?
时间: 2023-11-02 20:12:16 浏览: 33
如果成员名是一个指针,需要加上 `*` 运算符来获取指针所指向的地址。例如,假设结构体中的成员名为 `ptr_member`,指向某个结构体类型的指针,那么获取整个结构体的地址的代码如下:
```c
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
/* 示例结构体 */
struct student {
char name[20];
int age;
int score;
struct list_head list;
struct course *ptr_course;
};
/* 示例使用 */
struct student stu;
struct course *p_course;
/* 假设我们已经有一个指向 course 结构体的指针 p_course,需要获取整个 student 结构体的地址 */
p_course = stu.ptr_course;
struct student *pstu = container_of(p_course, struct student, ptr_course);
```
这里的 `ptr` 是指向结构体中某个成员的指针,`type` 是结构体的类型,`member` 是结构体中的成员名。在 `typeof` 中,由于 `ptr_member` 是一个指针,因此需要加上 `*` 运算符才能获取到指针所指向的类型。