函数指针基础详解

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//指针函数
//返回指针
int*fun()
{
    int*p = (int*)malloc(sizeof(int));
    return p;
}
int fun(int a)
{
    printf("a=======%d\n",a);
    return 0;

}
int fun1(int x, int y)
{
    return x + y;
}
//多态,多种形态,调用同一接口,不一样变现
//框架 固定变量 
void fun2(int x, int y, int(*p)(int a, int b))
{
    int a = p(x, y);//回调函数
    printf("%d", a);
}
int main()
{
    //函数指针,他是指针,指向函数的指针
    //定义函数指针变量有3种方式
    //1。先定义函数类型,再根据类型定义指针变量(不常用)
    //有typedef是类型 没有是变量
    typedef int FUN(int a);
    FUN *p1 = NULL;//函数指针变量
    p1 = fun;//p1指向函数fun 
    fun(5);//传统调用
    p1(6);
    //2.先定义函数指针类型,根据类型定义指针变量
    typedef int(*PFUN)(int a);//PFUN 函数指针类型
    PFUN p2 = fun;//p2指向fun
    //3。直接定义函数指针(常用)
    int(*p3)(int a) = fun;//合法的
    //函数指针数组
    int(*p3[2])(int a) = { fun, 0 };
    //函数的参数是变量 可以是函数指针变量吗 可以
    fun2(3, 4, fun1);
    printf("\n");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_23859701/article/details/80343315