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

Mi manca qualcosa qui. Per favore aiutami a sistemare questo. Grazie.dichiarazione anticipata di una struttura in C?

+2

C non consente solo dire 'contesto * qualunque ; ', lo fa? Ho pensato che ti ha fatto dire "struct context * qualunque cosa" ... – cHao

risposta

26

Prova questa

#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

grazie, ha funzionato! :) – user1128265

20

una struct (senza un typedef) spesso ha bisogno di (o dovrebbe) essere con la parola chiave struct quando viene utilizzato.

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

Se typedef vostra struct si può lasciare fuori la parola chiave struct.

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

Si noti che è legale riutilizzare il nome struct

provare a cambiare la dichiarazione anticipata a questo nel codice:

typedef struct context context; 
Problemi correlati