[問題] c語言array裡放function

看板C_and_CPP (C/C++)作者 (JimmyChung)時間14年前 (2012/01/04 22:23), 編輯推噓1(104)
留言5則, 4人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) IAR 8051 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) no 問題(Question): 各位大大,小弟想請問一下,我是否能在array裡放function,如下: #include <stdio.h> #include <stdlib.h> void test( void ) { printf( "test\n" ); } void test1( void ) { printf( "test1\n" ); } void test2( void ) { printf( "test2\n" ); } void ( *p[3] )( void ); int main() { p[0] = test; p[1] = test1; p[2] = test2; int nu; printf( "nu = " ); scanf( "%d", &nu ); p[nu]; return 0; } 用一個array把test,test1,test2這些function放到array,使用者只要輸入nu 就用array[nu],去呼叫function出來. 主要是因為我會有很多swtich case,我想要用這個方式去取,不知這樣是否可以? 想請問各位大大,我那裡的想法有錯誤? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.217.230.190 ※ 編輯: jimmycch 來自: 61.217.230.190 (01/04 22:31)

01/04 22:33, , 1F
給值沒問題 問題在呼叫 你需要加上 () 告訴編譯器你想呼叫
01/04 22:33, 1F

01/04 22:33, , 2F
函數指針嗎﹖
01/04 22:33, 2F

01/04 22:34, , 3F
也就是寫成 p[nu]() 這個樣子
01/04 22:34, 3F

01/04 23:56, , 4F
function pointer array
01/04 23:56, 4F

01/05 22:27, , 5F
謝謝各位大大的幫忙
01/05 22:27, 5F
文章代碼(AID): #1F163KqC (C_and_CPP)
文章代碼(AID): #1F163KqC (C_and_CPP)