观察下述代码:
typedef struct student {
char* name; //可以存char *a = “hellow world”; 可以当一个字符串 他的地址是第一个字母h
int age;
int (*init)(void);//一个指向无参数、返回类型为int的函数的指针。后面需要用到就成员名点方法
struct student* classmate;//一个指向student结构体的指针
}student, * pstudent;//结构体变量名,结构体指针
//void (*init)(void);
int GPIOKeyInit(void)
{
printf("KAL_GPIOKkeyInit();\r\n");
return 0;
}
int main()
{
student zhangshan = {
"zhangshan",
10,
GPIOKeyInit,
NULL
};
student lili = {
"lili",
15,
GPIOKeyInit,
NULL
};
zhangshan.classmate = &lili;
lili.classmate = &zhangshan;
zhangshan.init();
printf("%d\r\n", zhangshan.classmate->age);
return 0;
}
运行结果:KAL_GPIOKkeyInit(); 15
typedef struct lcd_operation {
int type;
void (*draw_logo)(void);
}lcd_operation, * plcd_operation;
void LCD_Show(void)
{
printf("LCD_Init 2\r\n");
}
void RGB_Show(void)
{
printf("RGB_Init\r\n");
}
int get_lcd_type(void)
{
return 0;
}
lcd_operation xxx_lcd[] = {
{0,LCD_Show},
{1,RGB_Show}
};
plcd_operation get_lcd(void)
{
int type = get_lcd_type();
return &xxx_lcd;//默认指向成员首地址 也就是xxx_lcd[0]
}
int main()
{
plcd_operation lcd;//利用结构体指针 定义的成员
lcd = get_lcd();//当然要用结构体指针定义的方法来赋值
//因为结构体方法中返回了 结构体成员的地址 所以可以访问到方法
(lcd+1)->draw_logo();
lcd->draw_logo();
printf("%d\r\n",lcd->type);
printf("%d\r\n",(lcd+1)->type);
xxx_lcd[0].draw_logo();//利用结构体变量定义的一个成员
#ifdef LCD_TYPE_A
LCD_Show();
#else
RGB_Show();
#endif
return 0;
}
运行结果: RGB_Init LCD_Init 2 0 1 LCD_Init 2 RGB_Init