指针函数
指针函数:是一个函数,返回值是一个指针;
eg1:在栈区开辟
//指针函数举例,输出一串字符
//1、在栈区进行
#include <stdio.h>
#include <string.h>
#include <malloc.h>
char* test01(){
static char str[20] = {0};//注意这里要使用定义为静态变量,不然出函数后,被销毁。
strcpy(str, "Hello world");
return str;
}
int main(){
char* p = NULL;
p = test01();
printf("%s\n", p);
return 0;
}
eg2:在堆区开辟
#include <stdio.h>
#include <string.h>
#include <malloc.h>
char* test02(){
char* str = (char*)malloc(20);
if(str == NULL){
printf("err\n");
return str;
}
strcpy(str, "Hello world!");
return str;
}
int main(){
int *p = NULL;
p = test02();
if(p != NULL){
printf("%s\n", p);
free(p);
}
return 0;
}
函数指针
函数指针:是一个指针,指针指向函数;一般可用作回调函数使用。
eg:
#include <stdio.h>
#include <string.h>
#include <malloc.h>
int (*Fun)(int, int);//函数指针声明
int add(int a, int b){
return a + b;
}
int sub(int a, int b){
return a - b;
}
int test(int a, int b, int (*Fun)(int, int)){
return ((*Fun)(a, b));
}
int main()
{
int x = 15, y = 12;
#if 0 //第1种调用方式
Fun = add;
printf("%d\n", (*Fun)(x, y));
Fun = sub;
printf("%d\n", (*Fun)(x, y));
#endif
#if 0 //第2种调用方式
printf("%d\n", test(x, y, add));
printf("%d\n", test(x, y, sub));
#endif
return 0;
}
使用typedef 创建自定义函数类型,回调函数的应用
就是将回调函数的参数作为被调用函数的参数执行,规定了被调用函数的返回值类型,参数类型和参数个数等。
eg:
#include <stdio.h>
typedef int (*F)(int, int);
int F1(int a, int b){
return a + b;
}
int F2(F S, int x, int y){
return S(x, y);
}
int main()
{
int x = 12, y = 15;
printf("%d\n", F2(F1, x, y));
return 0;
}