房产网站案例,wordpress商城源码,宜宾营销型网站建设,自己创建公司结构体里经常看到函数指针的写法#xff0c;函数指针其实就是函数的名字。但是结构体里你要是直接把一个函数摆上去#xff0c;那就变成成员变量#xff0c;就会发生混乱
1. 函数指针
#include unistd.h
#include stdio.hstruct Kiwia{void (*func)(int )…结构体里经常看到函数指针的写法函数指针其实就是函数的名字。但是结构体里你要是直接把一个函数摆上去那就变成成员变量就会发生混乱
1. 函数指针
#include unistd.h
#include stdio.hstruct 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.hvoid 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;
}