2013-03-25 14 views
5

Ho incontrato un problema particolare. Potrebbe essere meglio mostrarti solo quello che sto cercando di fare e poi spiegarlo.Inoltro dichiarazione di funzione puntatore typedef

typedef void functionPointerType (struct_A * sA); 

typedef struct 
{ 
    functionPointerType ** functionPointerTable; 
}struct_A; 

Fondamentalmente, presentano una struttura struct_A con un puntatore a una tabella di puntatori a funzione, che hanno un parametro di tipo struct_A. Ma non sono sicuro di come ottenere questa compilazione, in quanto non sono sicuro di come o se possa inoltrare la dichiarazione.

Qualcuno sa come questo potrebbe essere raggiunto?

edit: correzione minore in codice

risposta

9

avanti dichiarano come lei suggerisce:

/* Forward declare struct A. */ 
struct A; 

/* Typedef for function pointer. */ 
typedef void (*func_t)(struct A*); 

/* Fully define struct A. */ 
struct A 
{ 
    func_t functionPointerTable[10]; 
}; 

Ad esempio:

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

struct A; 

typedef void (*func_t)(struct A*); 

struct A 
{ 
    func_t functionPointerTable[10]; 
    int value; 
}; 

void print_stdout(struct A* a) 
{ 
    printf("stdout: %d\n", a->value); 
} 

void print_stderr(struct A* a) 
{ 
    fprintf(stderr, "stderr: %d\n", a->value); 
} 

int main() 
{ 
    struct A myA = { {print_stdout, print_stderr}, 4 }; 

    myA.functionPointerTable[0](&myA); 
    myA.functionPointerTable[1](&myA); 
    return 0; 
} 

uscita:

 
stdout: 4 
stderr: 4 

Vedi demo online http://ideone.com/PX880w.


Come altri hanno già accennato è possibile aggiungere:

typedef struct A struct_A; 

prima il puntatore alla funzione typedef e definizione completa di struct A se è preferibile omettere la parola chiave struct.

+0

la sintassi per questo mi ha sempre buttato fuori. – Claudiu

+0

"Come altri hanno già detto" Effettivamente. Puoi anche metterlo nella tua risposta e poi posso cancellare il mio. Penso che renderebbe la tua risposta migliore ed è quella che è salito in cima. –

+0

@DavidHeffernan, grazie. L'esempio è ideato e l'utilità del 'typedef' aggiuntivo non è realmente trasmessa (' struct A' o 'struct_A'). – hmjd

1

credo che questo è quello che stai cercando:

//forward declaration of the struct 
struct _struct_A;        

//typedef so that we can refer to the struct without the struct keyword 
typedef struct _struct_A struct_A;    

//which we do immediately to typedef the function pointer 
typedef void functionPointerType(struct_A *sA); 

//and now we can fully define the struct  
struct _struct_A       
{ 
    functionPointerType ** functionPointerTable; 
}; 
0

C'è un altro modo per farlo:

typedef struct struct_A_ 
{ 
    void (** functionPointerTable) (struct struct_A_); 
}struct_A; 


void typedef functionPointerType (struct_A); 
Problemi correlati