c语言函数指针应用
函数指针
函数指针是指向函数的指针变量。通常我们说的指针变量是指向一个整型、字符型或数组等变量,而函数指针是指向函数。函数指针可以像一般函数一样,用于调用函数、传递参数。
函数指针变量的声明:typedefint(\*fun\_ptr)(int,int);// 声明一个指向同样参数、返回值的函数指针类型。
以下实例声明了结构体函数指针变量 p,指向函数showStuInfo:
#include <stdio.h> #include <stdlib.h> #include <string.h> void showStuInfo(int age,char* name){ char buffer[1024] = {0}; char* preSuffix="年龄:"; char ageSuffix[10] = {0}; itoa(age,ageSuffix, 10); //将int转换成字符串 strcat(buffer,preSuffix); //字符串复制 strcat(buffer, ageSuffix); char* nameSuffix=" 姓名:"; strcat(buffer, nameSuffix); strcat(buffer, name); printf("sut=%s",buffer); } struct Student{ int age; char *name; void(* p)(int,char*); //声明函数指针 }; int main(int argc, char *argv[]) { struct Student student; struct Student* stu = &student; (*stu).age=20; (*stu).name="liuping"; (*stu).p = &showStuInfo; //把函数指针指向showStuInfo函数
stu->p((*stu).age,(*stu).name); return 0; }
#include
#include
#include
/* run this program using the console pauser or add your own getch, system(“pause”) or input loop */
void showStuInfo(int age,char* name){
char buffer[1024] = {0};
char\* preSuffix="年龄:";
char ageSuffix\[10\] = \{0\};
itoa(age,ageSuffix, 10);//将int转换成字符串
strcat(buffer,preSuffix);
strcat(buffer, ageSuffix);
char\* nameSuffix=" 姓名:";
strcat(buffer, nameSuffix);
strcat(buffer, name);
printf("sut=%s",buffer);
}
struct Student\{
int age;
char \*name;
void(\* p)(int,char\*);
\};
int main(int argc, char *argv[]) {
struct Student student;
struct Student* stu = &student;
(*stu).age=20;
(*stu).name=”liuping”;
(*stu).p = &showStuInfo;
stu->p((*stu).age,(*stu).name);
return 0;
}
在ide上运行打印结果如下:
还没有评论,来说两句吧...