2013-03-25 140 views
5

我遇到了一个奇怪的问题。告诉你我想要做什么然后解释它可能是最好的。函数指针的前向声明typedef

typedef void functionPointerType (struct_A * sA); 

typedef struct 
{ 
    functionPointerType ** functionPointerTable; 
}struct_A; 

基本上,我有一个结构struct_A的指针函数指针,谁具有struct_A类型的参数的表。但我不知道如何得到这个编译,因为我不知道如何或如果可以转发宣布这一点。

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

编辑:在代码中轻微修复

回答

9

正向声明为你的建议:

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


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

函数指针 typedefstruct A完整定义,如果优选的是省略 struct关键字
typedef struct A struct_A; 

之前。

+0

的语法,这总是把我摔下。 – Claudiu 2013-03-25 22:09:50

+0

“正如其他人已经提到”的确。你可能只是把它放入你的答案,然后我可以删除我的。我认为这会让你的回答更好,而且是最高的。 – 2013-03-25 22:24:56

+0

@DavidHeffernan,谢谢。这个例子是人为设计的,额外的'typedef'的用处并没有被真正传达('struct A'或'struct_A')。 – hmjd 2013-03-25 22:28:32

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

还有另一种方式来做到这一点:

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


void typedef functionPointerType (struct_A);