2010-05-19 240 views
6

我試圖創建一個函數指針,它將一個函數指針作爲參數,但我不知道該如何去做......我被建議嘗試鍵入我的函數指針之一,但得到相同的錯誤。有人可以用正確的語法來幫助我嗎?創建一個函數指針,它將一個函數指針作爲參數

int 
186 main(int argc, char **argv) 
187 { 
188 int    i; 

194 typedef int (*search_alg) (int *, int, int); 
195 typedef int (*search) (search_alg); 
196 set_t   (*intersect_alg) (list_t *, (search)); 
197 
198 clo_t   *iopts = parse_args(argc, argv); 
199 
200 /* select interstion algorithm */ 
201 switch (iopts->imode) { 
202 case SVS: 
203  fprintf(stdout, "ALGORITHM : SvS\n"); 
204  intersect_alg = svs; 
205  break; 
206 case SEQ: 
207  fprintf(stdout, "ALGORITHM : Sequential\n"); 
208  intersect_alg = sequential; 
209  break; 
210 case ADP: 
211  fprintf(stdout, "ALGORITHM : Adaptive\n"); 
212  intersect_alg = adaptive; 
213  break; 
214 default: 
215  fprintf(stdout, "ALGORITHM : Unknown\n"); 
216  return (EXIT_FAILURE); 
217 } 
218 
219 /* select fsearch algorithm */ 
220 switch (iopts->mode) { 
221 case LIN: 
222  fprintf(stdout, "F-SEARCH : Linear\n"); 
223  search = linear_fsearch; 
224  break; 
225 case BIN: 
226  fprintf(stdout, "F-SEARCH : Binary\n"); 
227  search = binary_fsearch; 
228  break; 
229 case INP: 
230  fprintf(stdout, "F-SEARCH : Interpolation\n"); 
231  search = interpolation_fsearch; 
232  break; 
233 case EXP: 
234  fprintf(stdout, "F-SEARCH : Exponential\n"); 
235  search = exponential_fsearch; 
236  break; 
237 default: 
238  fprintf(stdout, "F-SEARCH : Unknown\n"); 
239  return (EXIT_FAILURE); 
240 } 
241 

244 
245 /* perform intersection and run timings */ 
246 for (i = 0; i < iopts->runs; i++) { 
248  /* perform intersect search */ 
249  intersect_alg (iopts->data_files, search); 
252 } 

我試圖讓工作線是249,我最初試圖

int (*search_alg) (int *, int, int); 
set_t (*intersect_alg) (list_t *, (*) (int *, int, int); 

,並可能會喜歡,如果能做到這樣。我得到的錯誤是:

main.c:204: warning: assignment from incompatible pointer type 
main.c:208: warning: assignment from incompatible pointer type 
main.c:212: warning: assignment from incompatible pointer type 

而且我指着職能是:

 22 /** Finger Search Operations for array sets **/ 
23 int    linear_fsearch(int *set, int len, int key); 
24 int    binary_fsearch(int *set, int len, int key); 
25 int    interpolation_fsearch(int *set, int len, int key); 
26 int    exponential_fsearch(int *set, int len, int key); 
27 
28 /** Intersect Algorithms **/ 
29 set_t   *svs(list_t * list, int (*srch_alg) (int *, int, int)); 
30 set_t   *sequential(list_t * list, int (*srch_alg) (int *, int, int )); 
31 set_t   *adaptive(list_t * list, int (*srch_alg) (int *, int, int)); 

有人能看到我在做什麼錯?我無法弄清楚。 謝謝!

Rhys。

回答

9

你需要intersect_alg的聲明是

set_t *(*intersect_alg)(list_t *, int (*)(int *, int, int)); 
+0

啊,這似乎已經奏效! (沒有編譯錯誤)非常感謝。但我不確定我是否理解其背後的邏輯。爲什麼額外的星號? – 2010-05-19 13:19:01

+0

哦,等等,我明白了......很明顯。乾杯。 – 2010-05-19 13:19:40

+0

爲了創建這個,我只是接受'svs'的聲明,刪除了參數名稱,並用'(* intersect_alg)'替換了'svs'。 – caf 2010-05-19 13:28:23