C语言复习第五章:函数指针

    技术2022-07-10  177

    希望写一篇来把函数指针的内容回顾一下

    函数的指针的两种定义方法及三种使用方法 int myfun(int a,char b) { printf("int myfunc\n"); return 0; } int test01() { //函数指针写法一 typedef int(TYPE_FUN)(int,char); TYPE_FUN *f = myfun; //三种用法 f(10,'a'); (*f)(20,'b'); myfun(30,'c'); //函数指针写法二 int (*f2)(int,char) = NULL; f2 = myfun; f2(40,'d'); } 函数指针数组的使用方法 int fun01() { printf("fun01()"); } int fun02() { printf("fun02()"); } int fun03() { printf("fun03()"); } //函数指针数组 int test02() { int i; int (*fun_array[3])(); /* 换成void类型void value not ignored as it ought to be*/ fun_array[0] = fun01(); fun_array[1] = fun02(); fun_array[2] = fun03(); for(i = 0;i < 3;i++) { fun_array[i](); } return 0; } 函数指针做参数 打印数组元素 //函数指针做参数 回调函数 void printfall(void *a,int elsesize,int size,void(*print)(void *)) { char *a1 = (char*)a; int i ; for(i = 0;i < size;i++) { printf("%d\n",a + i*elsesize);//与原数组地址做对比 print(a + i*elsesize);//调用myprint函数,打印出数组元素 } } void myprintf(void *a) { int *a2 = (int *)a; printf("%d\n",*a2); } void test03() { int i; int a[] = {1,2,3,4,5}; printfall(a,sizeof(int),sizeof(a)/sizeof(int),myprintf); /* 打印数组各元素地址 printf("--------------------\n"); for(i = 0;i < 5;i++) { printf("%d\n",&a[i]); } */ } 做参数,打印出结构体数组元素 typedef struct person { char name[64]; int age; }person; void printfalls(void *a,int elsesize,int size,void(*print)(void *)) { char *a1 = (char*)a; int i; for(i = 0;i < size;i++) { char *pers = a1+i*elsesize; print(pers); } } void myprintfs(void*per) { person *p = (person*)per; printf("name:%s,age:%d\n",p->name,p->age); } void test04() { int i; person per[] = { {"aaa",64}, {"bbb",65}, {"ccc",66}, }; /* for(i = 0;i < 3;i++) { printf("%d\n",&per[i]); } */ printfalls(per,sizeof(person),sizeof(per)/sizeof(person),myprintfs); }
    Processed: 0.068, SQL: 12