函数指针typedef的前向声明

时间:2013-03-25 22:02:05

标签: c function-pointers typedef forward-declaration

我遇到了一个特殊的问题。最好只是告诉你我想要做什么然后解释它。

typedef void functionPointerType ( struct_A * sA );

typedef struct
{
    functionPointerType ** functionPointerTable;
}struct_A;

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

任何人都知道如何实现这一目标?

编辑:代码中的小修复

3 个答案:

答案 0 :(得分:10)

按照你的建议转发声明:

/* 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;
}

输出:

stdout: 4
stderr: 4

参见在线演示http://ideone.com/PX880w


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

typedef struct A struct_A;

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

答案 1 :(得分:1)

我认为这就是你要找的东西:

//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;
};

答案 2 :(得分:0)

还有另一种方法:

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


 void typedef functionPointerType ( struct_A ); 
相关问题