2013-03-25 135 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);