c - 基本函数指针误解

标签 c function pointers

我有以下代码:

#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/

相关文章:

c - 字符数组是在 C 中表示字符串常量的另一种方式吗?

c++ - Iterator increment results 是一个新的迭代器吗?

c - 格式化代码以访问结构类型的数组索引

c - 格式化字符串漏洞

c - 使用 SSE 实现上述逻辑的可能性

c - 星星金字塔

javascript - 使用 Javascript 来提醒用户输入的最高和最低整数

PHP - 如何将全局变量传递给函数

function - 代理设置输入函数返回列表错误

c++ - C++中使用指针识别对象类型