可能重複:
Casting a function pointer to another type通過C中合法/定義的函數指針傳遞附加參數嗎?
假設我初始化與實際花費較少的參數則該函數指針定義的功能的函數指針,將功能仍然正確地執行,如果通過所述被叫函數指針?
我試圖與海灣合作委員會和它的工作如預期,但我不知道是否該行爲是跨編譯器/平臺上是一致的(我懷疑有些enviroments可能發泄在棧上破壞):
#include <stdio.h>
typedef void (*myfun)(int, int, int);
void test_a(int x, int y, int z) {
printf("test_a %d %d %d\n", x, y, z);
}
void test_b(int x, int y) {
printf("test_b %d %d\n", x, y);
}
int main() {
myfun fp;
fp = test_a;
fp(1, 2, 3);
fp = (myfun) test_b;
fp(4, 5, 6);
}
如果使用被動清理,它也可能會崩潰。 –
我明白了。如何定義不帶參數列表的函數指針類型,如'typedef void(* myfun)()'。在這種情況下,編譯器是否應該保證棧上參數的順序是「正確的」? – Askaga
@BillAskaga否:要「保證」你想要什麼,你可能需要確保目標函數和函數指針都使用[cdecl調用約定](http://en.wikipedia.org/wiki/X86_calling_conventions#cdecl )。 – ChrisW