2012-04-03 23 views
27
#include <stdio.h> 

struct context; 

struct funcptrs{ 
    void (*func0)(context *ctx); 
    void (*func1)(void); 
}; 

struct context{ 
    funcptrs fps; 
}; 

void func1 (void) { printf("1\n"); } 
void func0 (context *ctx) { printf("0\n"); } 

void getContext(context *con){ 
    con=?; // please fill this with a dummy example so that I can get this working. Thanks. 
} 

int main(int argc, char *argv[]){ 
funcptrs funcs = { func0, func1 }; 
    context *c; 
    getContext(c); 
    c->fps.func0(c); 
    getchar(); 
    return 0; 
} 

मुझे यहां कुछ याद आ रहा है। कृपया इसे ठीक करने में मेरी सहायता करें। धन्यवाद।सी में एक संरचना की आगे की घोषणा?

+2

सी आप सिर्फ इतना कहना 'संदर्भ नहीं करता है * जो कुछ भी ; ', है ना? मैंने सोचा कि यह आपको 'संरचना संदर्भ * जो कुछ भी कहता है;' ... – cHao

उत्तर

26

इस

#include <stdio.h> 

struct context; 

struct funcptrs{ 
    void (*func0)(struct context *ctx); 
    void (*func1)(void); 
}; 

struct context{ 
    struct funcptrs fps; 
}; 

void func1 (void) { printf("1\n"); } 
void func0 (struct context *ctx) { printf("0\n"); } 

void getContext(struct context *con){ 
    con->fps.func0 = func0; 
    con->fps.func1 = func1; 
} 

int main(int argc, char *argv[]){ 
struct context c; 
    c.fps.func0 = func0; 
    c.fps.func1 = func1; 
    getContext(&c); 
    c.fps.func0(&c); 
    getchar(); 
    return 0; 
} 
+0

धन्यवाद, यह काम किया! :) – user1128265

20

एक struct (एक typedef के बिना) का प्रयास अक्सर करने की जरूरत है (या होना चाहिए) जब इस्तेमाल किया कीवर्ड struct के साथ हो सकता है।

struct A;      // forward declaration 
void function(struct A *a); // using the 'incomplete' type only as pointer 

यदि आप अपनी संरचना टाइप करते हैं तो आप संरचना कीवर्ड छोड़ सकते हैं।

typedef struct A A;   // forward declaration *and* typedef 
void function(A *a); 

ध्यान दें कि यह अपने कोड में यह करने के लिए तत्पर घोषणा बदलते struct नाम पुन: उपयोग करने

कोशिश कानूनी है:

typedef struct context context;