【问题标题】:typedef with function this is asked but couldnt understand?typedef with function this 被问到但无法理解?
【发布时间】:2014-08-23 07:31:42
【问题描述】:

您好,我无法弄清楚函数指针在下面的代码中是如何 typedef 的。请谁能解释一下

 #include<stdio.h>
 typedef int(*fp)(int,int) ; this is typedef with function pointer i m unable to figure out?
 int sum (int,int);
 int main()
{
    fp p,q; // p, q become function pointer too how?
    p=sum;
    printf("%d\n",p(20,10));
}
 int sum(int i,int j)
{
    return(i+j);
}

【问题讨论】:

    标签: c function-pointers typedef


    【解决方案1】:

    嗯,没什么好理解的。您定义了一个新类型 int(*fp)(int, int)。这不是函数指针,而是函数指针类型。将 fp 与 float、int 或任何其他原始类型进行比较。然后声明上述类型的 p 和 q 并将具有相同类型(隐式)的函数 sum 分配给 p。

    【讨论】:

      【解决方案2】:

      函数有签名

      int NAME(int ,int );
      

      所以指向它的指针是

      int (*NAME_OF_POINTER)(int, int);
      

      要预测长名称,请为函数指针定义新类型

      typedef int (*NEW_TYPE_NAME)(int, int);
      

      并使用它。所以不是

      int (*myVar)(int, int) = sum;
      

      你现在可以写了

      NEW_TYPE_NAME myVar = sum;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-08
        • 2022-12-01
        • 2021-07-21
        • 2019-01-05
        • 1970-01-01
        • 2021-01-03
        • 2019-10-02
        • 1970-01-01
        相关资源
        最近更新 更多