2013-03-25 13 views
5

की अग्रेषित घोषणा मैंने एक असामान्य समस्या में भाग लिया है। यह दिखाने के लिए सबसे अच्छा हो सकता है कि मैं क्या करने की कोशिश कर रहा हूं और फिर इसे समझाऊं।फंक्शन पॉइंटर टाइपपीफ

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


के रूप में दूसरों को पहले से ही उल्लेख किया है इसे जोड़ने के लिए संभव है:

typedef struct A struct_A; 

पूर्व समारोह सूचक typedef और struct A से भरा परिभाषा अगर यह struct कीवर्ड छोड़ बेहतर है करने के लिए।

+0

वाक्य रचना इस के लिए हमेशा मुझसे दूर फेंक दिया। – Claudiu

+0

"जैसा कि दूसरों ने पहले से ही उल्लेख किया है" वास्तव में। आप इसे अपने उत्तर में भी डाल सकते हैं और फिर मैं अपना हटा सकता हूं। मुझे लगता है कि यह आपके उत्तर को बेहतर बना देगा और यह वह है जो शीर्ष पर चढ़ गया। –

+0

@ डेविड हेफरन, धन्यवाद। उदाहरण सामने आया है और अतिरिक्त 'टाइपपीफ' की उपयोगिता वास्तव में व्यक्त नहीं की गई है ('संरचना ए' या' struct_A')। – hmjd

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); 
संबंधित मुद्दे