【问题标题】:Basic C Pointer and Functions基本 C 指针和函数
【发布时间】:2012-11-19 21:37:14
【问题描述】:

我试图弄清楚函数声明的含义:

int *f();

int (*g)();

【问题讨论】:

    标签: c function pointers function-pointers


    【解决方案1】:
    int *f();
    

    上面一行是函数f的声明,它具有未指定数量的参数并返回int *

    int (*g)();
    

    上面的行是一个指针g的声明,指向一个具有未指定数量的参数并返回一个int的函数。

    【讨论】:

    • int (*f()) 有什么改变吗?
    • @calccrypto 与int *f();的声明相同
    • @calccrypto,这与您的 int *f() 示例相同。它只是多了一组括号。
    【解决方案2】:

    作为对此处其他正确答案的补充,我想我会提到cdecl(1) 是用于破译此类声明的便捷工具:

    $ cdecl
    Type `help' or `?' for help
    cdecl> explain int *f();
    declare f as function returning pointer to int
    cdecl> explain int (*g)();
    declare g as pointer to function returning int
    

    cdecl 可能已经安装在您的机器上,或者您可以通过方便的网络界面在http://cdecl.org 上使用它。

    【讨论】:

      【解决方案3】:

      f 是一个函数,返回int*g 是一个指向返回int 的函数的指针。

      【讨论】:

        【解决方案4】:

        函数调用()等后缀运算符的优先级高于*等一元运算符,所以

        T *f();
        

        读作

           f     -- f
           f()   -- is a function (() binds before *)
          *f()   -- returning a pointer
        T *f();  -- to T (for some type T)
        

        如果你想强制*()之前绑定,你必须用括号显式分组,所以

        T (*g)();
        

        读作

            g     -- g
          (*g)    -- is a pointer
          (*g)()  -- to a function
        T (*g)(); -- returning T.  
        

        数组的规则类似:T *a[N] 是指向T 的指针数组,而T (*p)[N] 是指向T 数组的指针。

        【讨论】:

          猜你喜欢
          • 2012-02-17
          • 2018-09-12
          • 1970-01-01
          • 2023-03-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-09
          • 1970-01-01
          相关资源
          最近更新 更多