2012-04-03 93 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不會讓你剛纔說'上下文*什麼;',是嗎?我以爲肯定它讓你說'結構上下文*什麼;'... – cHao 2012-04-03 18:53:20

回答

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 2012-04-03 19:15:48

20

一個結構(沒有一個typedef)通常需要(或應)一起使用時是與關鍵字結構。

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

如果您輸入您的結構,您可以省略struct關鍵字。

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

注意,它是合法的重用結構名稱

嘗試改變向前聲明本在你的代碼:

typedef struct context context;