【问题标题】:Forward declaration of function pointer typedef函数指针 typedef 的前向声明
【发布时间】:2013-03-25 22:02:04
【问题描述】:

我遇到了一个特殊的问题。最好只是向您展示我正在尝试做的事情然后解释它。

typedef void functionPointerType ( struct_A * sA );

typedef struct
{
    functionPointerType ** functionPointerTable;
}struct_A;

基本上,我有一个结构struct_A,其中有一个指向函数指针表的指针,函数指针具有struct_A 类型的参数。但我不确定如何编译,因为我不确定如何或是否可以转发声明。

有人知道如何实现吗?

编辑:代码中的小修复

【问题讨论】:

    标签: c function-pointers typedef forward-declaration


    【解决方案1】:

    按照您的建议转发声明:

    /* Forward declare struct A. */
    struct A;
    
    /* Typedef for function pointer. */
    typedef void (*func_t)(struct A*);
    
    /* Fully define struct A. */
    struct A
    {
        func_t functionPointerTable[10];
    };
    

    例如:

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    struct A;
    
    typedef void (*func_t)(struct A*);
    
    struct A
    {
        func_t functionPointerTable[10];
        int value;
    };
    
    void print_stdout(struct A* a)
    {
        printf("stdout: %d\n", a->value);
    }
    
    void print_stderr(struct A* a)
    {
        fprintf(stderr, "stderr: %d\n", a->value);
    }
    
    int main()
    {
        struct A myA = { {print_stdout, print_stderr}, 4 };
    
        myA.functionPointerTable[0](&myA);
        myA.functionPointerTable[1](&myA);
        return 0;
    }
    

    输出:

    标准输出:4 标准错误:4

    查看在线演示http://ideone.com/PX880w


    正如其他人已经提到的,可以添加:

    typedef struct A struct_A;
    

    在函数指针typedefstruct A 的完整定义之前,如果最好省略struct 关键字。

    【讨论】:

    • 这个语法总是让我失望。
    • “正如其他人已经提到的”确实。您也可以将其放入您的答案中,然后我可以删除我的。我认为这会使您的答案变得更好,并且它是上升到顶部的答案。
    • @DavidHeffernan,谢谢。该示例是人为设计的,并没有真正传达附加 typedef 的有用性(struct Astruct_A)。
    【解决方案2】:

    我想这就是你要找的东西:

    //forward declaration of the struct
    struct _struct_A;                               
    
    //typedef so that we can refer to the struct without the struct keyword
    typedef struct _struct_A struct_A;              
    
    //which we do immediately to typedef the function pointer
    typedef void functionPointerType(struct_A *sA); 
    
    //and now we can fully define the struct    
    struct _struct_A                        
    {
        functionPointerType ** functionPointerTable;
    };
    

    【讨论】:

      【解决方案3】:

      还有另一种方法:

      typedef struct struct_A_
      {
          void  (** functionPointerTable) (struct struct_A_);
      }struct_A;
      
      
       void typedef functionPointerType ( struct_A ); 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-06-19
        • 1970-01-01
        • 1970-01-01
        • 2011-06-20
        • 1970-01-01
        • 1970-01-01
        • 2021-06-27
        相关资源
        最近更新 更多