我有以下代码:
#include <stdio.h>
#include <conio.h>
int fun1 (int);
int fun2 (int);
int fun3 (int);
int (*fun4) (int) = fun1; // 1
void main()
{
int (*fun4) (int) = fun2; // 2
printf ("%d\n", fun4(3));
printf ("%d\n", fun3(3));
getch();
}
int fun1 (int x)
{
return x+1;
}
int fun2 (int x)
{
return 2*x;
}
int fun3 (int x)
{
return fun4(x);
}
它产生输出:
6
4
我不确定为什么会这样。
在写//2的那一行,我们定义了fun4指向fun2。所以从那时起,当我写 fun4(x) 时,它就和写 fun2(x) 一样了。我不确定为什么第二次打印会产生 4。
谁能解释为什么会这样?
最佳答案
so from then on, when i write fun4(x) its the same as writing fun2(x). I'm not sure why the second print yields 4.
没有。
int (*fun4) (int) = fun2; // 2
仅在 main
范围内可见。 fun4
是仅在 main
内部指向 fun2
的指针。在 main
的范围之外 fun4
是指向 fun1
的指针。
当您在 fun3
中调用 fun4(x)
时,它等同于 fun1(x)
关于c - 基本函数指针误解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25961775/