我有一個函式指標陣列:
int (*collection[2]) (int input1, int input 2) = {&fct1,&fct2}
我可以通過從陣列中呼叫這兩個函式來獲取值:
*collection[0](1,2);
*collection[1](1,2);
使用 typedef,我想要另一種呼叫函式指標陣列的方法。到目前為止,我正在做:
typedef int (*alternameName)(int input1, int input 2);
alternateName p = &collection[2];
int result1 = (*p[0])(1,2);
int result2 = (*p[1])(1,2);
printf("results are: %d, %d",result1, result2);
我的問題是我認為我沒有正確定義變數 p 因為我的結果一直是 0。
uj5u.com熱心網友回復:
typedef 函式型別通常更干凈,而不是函式指標。它導致更清晰的語法:
typedef int collection_f(int, int);
現在您可以collection簡單地將 定義為指向 的陣列collection_f。
collection_f* collection[2] = {&fct1,&fct2};
典型的呼叫語法是:
collection[0](1,2);
collection[1](1,2);
不要在呼叫之前取消參考函式指標。實際上,呼叫運算子將??函式指標作為運算元,而不是函式。函式在所有背景關系中衰減為函式指標,除了&operator ... 回傳函式指標。
接下來,我不確定是什么:
alternateName p = &collection[2];
應該是這個意思。我假設您要p指向collection. 此外,索引p[1]和p[2]看起來像是越界訪問,因為訪問集合僅針對索引 0 和 1 定義。
現在您的代碼可以重寫可以:
collection_f** p = collection; // pointer to first element which is a pointer to collection_f
int result1 = p[0](1,2);
int result2 = p[1](1,2);
printf("results are: %d, %d",result1, result2);
我希望它能解決問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/430751.html
