一、函数指针:
函数名和变量名一样,也对应一个地址。
#include <stdio.h>
void example(int n)
{
printf("test:n=%d \n",n);
}
int main()
{
printf("%08x \n",&example);
return 0;
}
实际上,每个函数在编译后都有对应一串指令,这些指令在内存中的位置就是函数地址,和变量一样,我们可以用一个指针类型来表示函数的地址。
void (*p) (int):
变量名:p
变量类型:函数指针,记作 void (int)*
返回值为void,参数为(int)的函数。
p=&example;
由于example是这样的函数,所以可以赋值。
函数的指针就是指向函数的地址。
#include <stdio.h>
void example(int n)
{
printf("test:n=%d \n",n);
}
void example2(int a,int b)
{
printf("test:a=%d,b=%d\n",a,b);
}
int main()
{
/*printf("%08x \n",&example);*/
void (*p) (int);
p=&example;
void (*p2)(int,int);
p2=&example2;
return 0;
}
一、函数指针的调用:
普通指针,用于读写目标内存里的值。
int* p;p=&a;*p=123;//修改目标内存。
函数指针:用于调用目标函数。
void (*p) (int);
p=&example;
p(123);//调用目标函数。
也是就说,当知道了一个函数的地址和类型,就能够调用这个函数。
#include <stdio.h>
void example(int a)
{
printf("test=%d \n",a);
}
int main()
{
//方式1:
//void (*p)(int);
//p=&example;
//p(123);
//方式2:
typedef void (*PFUNCTION)(int);//定义函数指针类型
PFUNCTION p=&example;
p(123);
return 0;
}
函数指针做为参数的用法:
#include <stdio.h>
void example(int a)
{
printf("a=%d \n",a);
}
typedef void (*PFUNCTION)(int);
// void test (PFUNCTION f)
// {
// f(123);
// }
void test(PFUNCTION f,int n)
{
f(n);
}
int main()
{
//方式1:
//void (*p)(int);
//p=&example;
//p(123);
//方式2:
//定义函数指针类型
// PFUNCTION p=&example;
//
// p(123);
/*test(&example);*/
//函数指针可以作为参数
test(&example,12);
return 0;
}