2013-03-25 25 views
5

Wpadłem na osobliwy problem. Najlepiej po prostu pokazać, co próbuję zrobić, a potem to wyjaśnić.Wskaźnik deklaracji funkcji do przodu typedef

typedef void functionPointerType (struct_A * sA); 

typedef struct 
{ 
    functionPointerType ** functionPointerTable; 
}struct_A; 

Zasadniczo mam strukturę struct_A ze wskaźnikiem do tablicy wskaźników funkcji, które mają parametr typu struct_A. Ale nie jestem pewien, jak skompilować tę kompilację, ponieważ nie jestem pewien, jak lub czy można ją przesłać dalej.

Ktoś wie, jak to osiągnąć?

edit: drobne poprawki w kodzie

Odpowiedz

9

przodu zadeklarować jak sugerujesz:

/* 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]; 
}; 

Na przykład:

#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; 
} 

wyjściowa:

 
stdout: 4 
stderr: 4 

Zobacz demo on-line http://ideone.com/PX880w.


Jak inni już wspomniano jest to możliwe, aby dodać:

typedef struct A struct_A; 

przed wskaźnika funkcji typedef i pełnej definicji struct A jeśli zaleca się pominięcie słowa kluczowego struct.

+0

składnia to zawsze wyrzucił mnie. – Claudiu

+0

"Tak jak inni już wspomnieli" Rzeczywiście. Równie dobrze możesz po prostu włożyć to do swojej odpowiedzi, a następnie mogę usunąć moje. Myślę, że poprawiłoby to twoją odpowiedź i to ona wzniosła się na szczyt. –

+0

@DavidHeffernan, dzięki. Przykład jest wymyślny, a użyteczność dodatkowego 'typedef' nie jest tak naprawdę przekazywana (' struct A' lub 'struct_A'). – hmjd

1

myślę, że to jest to, czego szukasz:

//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

Jest jeszcze jeden sposób, aby to zrobić:

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


void typedef functionPointerType (struct_A); 
Powiązane problemy