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

ここに何か不足しています。これを解決するのを手伝ってください。ありがとう。Cの構造体の前方宣言?

+2

Cは、あなただけのどんな* 'コンテキスト言わせません。あなたのコード内でこれに前方宣言を変更してみてください構造体名に

を再利用することが合法であることを

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

注意; 'それで?私はあなたが 'struct context * whatever; 'と言ったことを確信しました... ... – 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

(typedefはなし)構造体を試してみては、多くの場合に必要である(または必要があります)を使用する場合、キーワード構造体となります。

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

structをtypedefする場合は、structキーワードを省略することができます。

typedef struct context context; 
関連する問題