[問題] 函數指標的void*參數個數可不定?

看板C_and_CPP (C/C++)作者 (aMa)時間11年前 (2015/03/16 18:48), 11年前編輯推噓1(107)
留言8則, 3人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) VC++ 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 我看了別人的程式,當中他宣告一個function pointer, 其中引數部份有六個void*, 這個function pointer可以接受不同的回傳值型別或引數個數不定的function address, 我用VC++驗証如下: // void_ptr.cpp : main project file. #include "stdafx.h" #include <iostream> using namespace std; typedef bool (*func_ptr)(void* input0, void* input1, void* input2, void* input3, void* input4, void* input5, void* input6); bool func1(int* a, int* b){ cout << __FUNCTION__; return true; } bool func2(char* a, int* b, int* c){ cout << __FUNCTION__ ; return true; } bool func3(int* a, int* b, char* c, char* d){ cout << __FUNCTION__; return true; } void func4(int* a, int* b) { cout << __FUNCTION__; } void func5(void) { cout << __FUNCTION__; } static func_ptr list[]={ (func_ptr)&func1, (func_ptr)&func2, (func_ptr)&func3, (func_ptr)&func4, (func_ptr)&func5, }; int main(array<System::String ^> ^args) { void *g0, *g1, *g2,*g3, *g4, *g5, *g6; int x=10; int y=5; g0=&x; g1=&y; list[0](g0,g1,g2,g3,g4,g5,g6); char* str; str="hihihi"; g0=str; g2=&y; list[1](g0,g1,g2,g3,g4,g5,g6); list[4](g0,g1,g2,g3,g4,g5,g6); system("pause"); return 0; } 結果會印出func1func2func5,無任何錯誤 我一直以為function pointer只能接受與宣告時相同型別的 function address(回傳值,引數型別,引數個數), 別人的code是在linux下, 我的驗証是在vs2010 vc++, 這該如何解釋, void*可以接受任何位址, 但在轉成(func_ptr)時應該mapping錯才對... 餵入的資料(Input): 預期的正確結果(Expected Output): 錯誤結果(Wrong Output): 程式碼(Code):(請善用置底文網頁, 記得排版) 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.32.220.130 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1426502921.A.59A.html ※ 編輯: aMaa (114.32.220.130), 03/16/2015 18:50:23

03/16 18:51, , 1F
Koenig Lookup?
03/16 18:51, 1F

03/16 18:52, , 2F
ar...你問的應該不是這個 請忽略 XD
03/16 18:52, 2F

03/16 19:25, , 3F
都是一群指標傳來傳去,當然沒事,把 func1 的形式參數 a
03/16 19:25, 3F

03/16 19:26, , 4F
改成 double,就會有衝突,就會跟 func_ptr 形參有衝突
03/16 19:26, 4F

03/16 19:27, , 5F
然後雖然 list[1] 的參數個數,跟實際指向的函數需要的
03/16 19:27, 5F

03/16 19:28, , 6F
不同,可是堆疊的控制是 cdecl,所以不會損壞程式
03/16 19:28, 6F

03/16 23:01, , 7F
Undefined behavior, 只是 vc 剛好選擇直覺的輸出
03/16 23:01, 7F

03/16 23:01, , 8F
文章代碼(AID): #1L1hK9MQ (C_and_CPP)
文章代碼(AID): #1L1hK9MQ (C_and_CPP)