1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
| #include <stdio.h>
| #include <stddef.h>
|
| #define container_of(ptr, type, member) ({ \
| const typeof(((type *)0)->member) *__mptr = (ptr); \
| (type *)((char *)__mptr - offsetof(type, member)); \
| })
|
| struct student_s
| {
| char name[50];
| int age;
| };
|
| void print_student(int *p_age)
| {
| struct student_s *p_student;
|
| // 使用 container_of 获取指向 student_s 结构体的指针
| p_student = container_of(p_age, struct student_s, age);
|
| printf("Name: %s, Age: %d\n", p_student->name, p_student->age);
|
| return ;
| }
|
| int main(void)
| {
| struct student_s student = {"Zhang San", 30};
|
| print_student(&student.age);
|
| return 0;
| }
|
|