函数指针:定义一个指针,然后将函数地址赋值给这个指针,指针就等同于函数。
c展开代码#include <stdio.h>
int max(int x, int y)
{
    return x > y ? x : y;
}
int main(void)
{
    int (* p)(int, int) = & max; // &可以省略
    printf("最大的数字是: %d\n", p(2,3));
    return 0;
}
回调函数就是一个通过函数指针调用的函数:编写一个函数,另一个函数可以用这个函数当参数。下面中excutef就是回调函数。
c展开代码#include <stdio.h>
#include <stdlib.h>
int max( int x, int y )
{
 return(x > y ? x : y);
}
int excutef( int (*func)( int, int ), int arga, int argb )
{
 return( (*func)(arga, argb) );
}
int main( void )
{
 printf( " %d\n", excutef( max, 1, 2 ) );
 return(0);
}
把函数指针装入数组,然后调用:
c展开代码#include <stdio.h>
int max(int x, int y)
{
    return x > y ? x : y;
}
int min(int x, int y)
{
    return x < y ? x : y;
}
int main(void)
{
    int (*p[2])(int, int)={&max,&min};
    printf("%d   %d \n", p[0](2,3),p[1](2,3));
    return 0;
}
当结构体和函数指针在一起,就会产生很多东西。
c展开代码#include <stdio.h>
#include <stdlib.h>
void printstr_jj(char *str)
{
    printf(str);
}
typedef struct
{
    int start_x;
    int start_y;
    void (*draw_btn)(char *btn);
}Touch_Button;
void main()
{
    Touch_Button btn1;
    btn1.draw_btn=printstr_jj;
    btn1.draw_btn("test");
}
当结构体和函数指针在一起,就会产生很多东西。再加个数组。2
c展开代码#include <stdio.h>
#include <stdlib.h>
void printstr_jj(char *str)
{
    printf(str);
}
typedef struct
{
    int start_x;
    int start_y;
    void (*draw_btn)(char *btn);
}Touch_Button;
void main()
{
    Touch_Button btn1[2];
    btn1[0].draw_btn= printstr_jj;
    btn1[1].draw_btn= printstr_jj;
    btn1[0].draw_btn("test1");
    btn1[1].draw_btn("test2");
}
当结构体和函数指针在一起,就会产生很多东西。再加个数组。3
c展开代码#include <stdio.h>
#include <stdlib.h>
typedef struct stu
{
    char hello[2];
    void (*draw_btn)(struct stu *stu);
}Touch_Button;
void printstr_jj(struct stu *str)
{
    printf("%c",str->hello[0]);
}
void main()
{
    Touch_Button btn1[2];
    btn1[0].hello[0]='1';
    btn1[0].hello[1]='1';
    btn1[1].hello[0]='2';
    btn1[1].hello[1]='2';
    btn1[0].draw_btn= printstr_jj;
    btn1[1].draw_btn= printstr_jj;
    btn1[0].draw_btn(&btn1[0]);
    btn1[1].draw_btn(&btn1[1]);
}


本文作者:Dong
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC。本作品采用《知识共享署名-非商业性使用 4.0 国际许可协议》进行许可。您可以在非商业用途下自由转载和修改,但必须注明出处并提供原作者链接。 许可协议。转载请注明出处!