C语言函数指针的理解

#if !defined (STDIO_H)
#define STDIO_H
#include <stdio.h>
#endif

#if !defined (STDLIB_H)
#define STDLIB_H
#include <stdlib.h>
#endif

typedef struct __student {
    int age;
    void (*myFunctionPointer)(struct __student *who);//myFunctionPointer表示函数指针变量名,void表示函数指针指向的函数返回类型,struct __student *who表示函数指针指向函数的参数类型
} Student_TypeDef;

//这里定义Student_TypeDef的时候也写上了结构体的名字:__student,这样写法既可以作结构体使用也可以作Student_TypeDef别名类型使用

struct animal {
    int ok;
};

void bb(struct __student *who) {
    printf("bb函数开始执行:%2d\r\n", who->age);
}

int main(int argc, char *argv) {
    printf("test typedef struct name\r\n");
    Student_TypeDef a;//作Student_TypeDef别名类型使用的时候直接声明即可
    a.age = 0xF;
    a.myFunctionPointer = &bb;
    printf("a.age:%2d\r\n", a.age);
    struct animal;
    struct __student b;//作结构体使用的时候需要在前面加上struct关键字
    b.age = 31;
    printf("打印结构体名字是__student的b的年龄:%2d\r\n", b.age);
    a.myFunctionPointer(&b);//调用函数指针指向的函数
    return 0x00;
}

posted @ 2025-04-05 14:46  JianfeiMa  阅读(4)  评论(0)    收藏  举报