指针函数
#include <stdio.h>
int* fun(int* a)
{
return a;
}
int main()
{
int a = 10;
int* p = &a;
a = 20;
printf("%d", *fun(p)); // 20
return 0;
}
函数指针
#include <stdio.h>
int sum(int x, int y)
{
return x + y;
}
int main()
{
int (*p)(int, int) = sum;
int result1 = (*p)(1, 2);
int result2 = p(1, 2); // p(1, 2) == sum(1, 2)
return 0;
}
#include <stdio.h>
int sum(int x, int y)
{
return x + y;
}
int minus(int x, int y)
{
return x - y;
}
int operate(int (*p)(int, int), int x, int y)
{
return p(x, y); // 回调函数
}
int main()
{
int a = 1, b = 2;
int (*p)(int, int);
puts("请输入一个'+'或'-':");
while(1)
{
int operator = getchar();
if(operator == '+')
{
p = sum;
break;
}
else if(operator == '-')
{
p = minus;
break;
}
else puts("---Error---");
}
int result = operate(p, a, b);
printf("%d", result);
return 0;
}