--- title: Function Pointer Array tags: C++ Note --- Function Pointer Array --- 1. Initialization ```typescript= // 函式宣告如下 void func1(int int1, char char1); // 指向func1的指標如下: // 這樣的寫法應理解成:funcPtr1是一個函數指標,它指向的函數接受int與char兩個參數並回傳void。(signature) void (*funcPtr1)(int, char); // 函式指標指向函式1 funcPtr1 = &func1; // 也可以在宣告時就直接給予初值,則如下: void (*funcPtr1)(int, char) = &func1; //&亦可省略 ``` 2. With **typedef**: ```typescript= typedef int (*MathFunc)(float, int); int do_math(float arg1, int arg2) { return arg2; } int call_a_func(MathFunc call_this) { int output = call_this(5.5, 7); return output; } int final_result = call_a_func(do_math); // 7 ``` 3. Without **typedef**: ```typescript= int do_math(float arg1, int arg2) { return arg2; } int call_a_func(int (*call_this)(float, int)) { int output = call_this(5.5, 7); return output; } int final_result = call_a_func(do_math); // 7 ``` 4. Example ```typescript= void run() { printf("start\r\n"); } void stop() { printf("stop\r\n"); } void exit() { printf("exit\r\n"); } static void (*command[])(void) = {run, stop, exit}; int OnStateChange(uint state) { if (state > 3) { printf("Wrong state!\n"); return false; } command[state](); return 0; } ``` [補充] Function Pointer 可以拿來做什麼? - [鄉民範例](https://www.ptt.cc/man/C_and_CPP/DB9B/DE77/M.1138167685.A.A3D.html) - [英文範例](http://www.newty.de/fpt/intro.html#why)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up