2012-04-03 29 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; 
} 

Tôi thiếu gì đó ở đây. Xin hãy giúp tôi sửa cái này. Cảm ơn.tuyên bố trước về cấu trúc trong C?

+2

C không cho phép bạn chỉ nói 'bối cảnh * bất cứ điều gì ; ', phải không? Tôi nghĩ chắc chắn nó làm cho bạn nói 'struct context * bất cứ điều gì;' ... – cHao

Trả lời

26

Hãy thử điều này

#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

cảm ơn, nó đã hoạt động! :) – user1128265

20

Một struct (không có một typedef) thường cần (hoặc nên) được với các cấu trúc từ khóa khi sử dụng.

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

Nếu bạn đã nhập cấu trúc, bạn có thể bỏ từ khóa struct.

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

Lưu ý rằng nó là hợp pháp để tái sử dụng tên struct

Hãy thử thay đổi tuyên bố mong muốn này trong mã của bạn:

typedef struct context context;