1. 前言
函数指针:函数的指针,指向一个函数的指针,本质是一个指针;
指针函数:指针的函数,一个返回指针类型的函数,本质是一个函数。
对于一个函数,在编译时,会给该函数代码段分配一段存储地址,该存储地址的首地址就是这个函数的地址,而函数名表示的就是这个首地址。
函数指针在使用前需要注意3点:
1)声明一个函数;
2)定义一个函数指针;
3)将函数指针指向该函数。
2. 例子
例子1:
#include<stdio.h>
int Max(int, int);
int (*p)(int, int);
int main(void)
{
int a = 1;
int b = 2;
p = Max;
int c = (*p)(a, b);
printf("The Max Function value is: %d\n", c);
return 0;
}
int Max(int x, int y)
{
if(x > y)
return x;
else
return y;
}
例子2:
#include<stdio.h>
void populate_array(int *array, size_t arraySize, int (*getNextValue)(void))
{
for(size_t i = 0; i < arraySize; i++)
{
array[i] = getNextValue();
}
}
int getNextRandomValue()
{
return rand();
}
int main()
{
int array[10];
populate_array(array, 10, getNextRandomValue);
for(int i = 0; i< 10; i++)
printf("%d ", array[i]);
printf("\n");
return 0;
}