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

Ich vermisse etwas hier. Bitte helfen Sie mir, das zu beheben. Vielen Dank.Forward-Deklaration einer Struktur in C?

+2

C nicht lassen Sie nur sagen, 'Kontext * was auch immer ; ', oder? Ich dachte, es hätte dich dazu gebracht, 'struct context * was auch immer zu sagen;' ... – cHao

Antwort

26

diese

#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

danke, es hat funktioniert! :) – user1128265

20

eine Struktur Versuchen (ohne typedef) häufig bei der Verwendung (oder soll) sein mit dem Schlüsselwort struct muss.

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

Wenn Sie defdef Ihre Struktur eingeben, können Sie das Schlüsselwort struct weglassen.

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

Beachten Sie, dass es legal ist, die Struktur Name der Forward-Deklaration zu dieser

Versuchen zur Wiederverwendung in Ihrem Code zu ändern:

typedef struct context context;