【问题标题】:What does `int (*)(int)` in c mean with regard to type?c中的`int(*)(int)`对于类型意味着什么?
【发布时间】:2016-01-02 21:03:03
【问题描述】:

我有这个 C 代码(受测试启发)

#include <stdio.h>

int foo (int n)
{
    static int s = 0;
    return s += n;
}

int main()
{
    int y;
    int i;

    for (i=0; i<5; i++) {
        y= foo(i);
    }

    printf("%d\n", foo);

    return 0;
}

我对@9​​87654323@ 的值以及它的类型特别感兴趣。编译器给了我这个警告

test.c:18:16: warning: format specifies type 'int' but the argument has type
      'int (*)(int)' [-Wformat]

但我不太确定这意味着什么。什么是int (*)(int),调用不带参数的函数名如何给我这种类型的东西?

【问题讨论】:

  • 如果要获取foo的值,使用printf("%p", (void*)foo);,但标准不保证。类型见this

标签: c function types


【解决方案1】:

如果没有函数调用,foo 的计算结果是指向一个函数的指针,该函数接受 int 并返回 int。这就是int (*)(int)的详细描述。

【讨论】:

    【解决方案2】:

    你没有打电话给foo。要拨打foo,请在姓名后面加上(argument)。实际上,您获取foo 的地址,它的类型为int (*)(int)(指向采用一个整数参数并返回一个int 的函数的指针)并将其发送到printf。

    printf 然后抱怨,因为你试图告诉它打印一个int,但给它一个函数指针。

    【讨论】:

      猜你喜欢
      • 2013-01-16
      • 2012-01-15
      • 1970-01-01
      • 1970-01-01
      • 2015-07-30
      • 2012-01-03
      • 2014-12-07
      • 1970-01-01
      • 2020-10-12
      相关资源
      最近更新 更多