一个小例子,演示函数指针
结构体里经常看到函数指针的写法,函数指针其实就是函数的名字。但是结构体里你要是直接把一个函数摆上去,那就变成成员变量,就会发生混乱
1. 函数指针
#include <unistd.h>
#include <stdio.h>struct Kiwia{void (*func)(int );int argus;
};
void test1(int m){printf("m = %d\n", m);
}int main (){struct Kiwia obj1;obj1.func = test1;obj1.argus =300;(*test1)(300);// test1(300);
return 0;
}
编译成a.out 然后运行。。
注意,这两行代码你写哪行,最后都打印 m =300 ,说明test1就是函数指针。
(*test1)(300);
// test1(300);
这个我自己定义的Kiwia有俩成员,一个函数指针叫做 func ,一个叫做 argus是一个整数。
2. 函数指针当参数
还是刚才代码修改一下
#include <unistd.h>
#include <stdio.h>void test1(int m){printf("m = %d\n", m);
}void test2( void (*function)(int),int a1){printf("test2,\n");(*function)(a1);
}int main (){test2( test1,200);
return 0;
}
执行结果
test2
m = 200
3. 返回指针的函数
void * func (){return NULL;
}int* fuc2(){return NULL;
}
都返回指针,当然,不能返回局部变量的指针或者引用(除非开辟在堆上) ,所以调用这俩函数的时候,需要进行指针类型转换
(void*)func
(int *) fuc2
4. 实际应用
线程创建函数里有一个很让人崩溃的写法,现在才明白,这俩情况都有
#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
//返回值:成功返回0,失败返回错误编号
看第三个参数 void *(*start_routine) (void *)
说明,你要写pthread_create 这个函数的调用的时候,你括号里第三个参数必须写一个 函数指针。
然后这个函数start_routine的 返回值,还是void * 类型,你自己提前写start_routine函数的代码声明(定义)的时候,这样写
void * start_routin ( void* 你的参数){
return NULL;
}