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