這是非常簡單的,我正在嘗試去做,而我只是很難弄清楚正確的語法。如何在C中的struct中使用函數指針?
我希望我的結構看起來像這樣:
struct myStruct
{
functionPointer myPointer;
}
然後,我有另一項功能,在其他地方是通過一個函數的函數,並返回我的結構的一個實例。以下是它的作用:
struct myStruct myFunction(int (*foo) (void *))
{
myStruct c;
c.myPointer = foo;
return c;
}
我怎樣才能使這個實際工作?什麼是正確的語法:
- 在我的結構聲明一個函數指針(顯然
functionPointer myPointer;
是不正確的) - 分配函數的地址給函數指針(很肯定
c.myPointer = foo
是不正確的)?
如果你返回一個myStruct *,你應該分配(例如,使用malloc)並返回malloced值。如果你返回一個myStruct,你應該像這樣聲明你的函數。 (現在,你聲明該函數返回一個指針,但你試圖返回一個結構體。) – 2012-01-14 02:14:01
[C中的函數指針]的可能重複(http://stackoverflow.com/questions/1278841/)。另請參見[函數指針作爲C結構的成員](http://stackoverflow.com/questions/1350376/),[結構與指向函數的指針](http://stackoverflow.com/questions/2939003/) ,[typedef是你的朋友](http://stackoverflow.com/a/8028634/90527)。 – outis 2012-01-14 02:19:14