[英]how do I assign a function to an element of an array of function pointers
在Xcode 7.2.1中,我聲明了3個C函數
double function1(double);
double function2(double);
double function3(double);
現在,我聲明一個指向函數的指針並對其進行定義。
double (*aFunctionPointer)(double)=function1;
沒有預期的錯誤。
現在,我聲明一個函數指針數組,並用我的3個函數填充它。
double (*anArrayOfFunctionPointers[3])(double)={function1, function2, function3};
同樣,沒有錯誤。
現在,我定義了一個函數指針數組,但不填充它。
double (*anotherArrayOfFunctionPointers[3])(double);
同樣,沒有錯誤。
現在,我嘗試為一個數組元素分配一個函數。
anotherArrayOfFunctionPointers[1]=function2;
這次,警告和錯誤:
我感到難過。
背景是我試圖編寫一個在各種度量單位之間轉換的程序。 我以為我會使用一個包含函數指針的二維數組,以避免許多非常冗長的switch語句。
要進行轉換,我將調用以下函數:
result=convert(someValueToConvert,yards,meters);
並且convert函數將從數組中調用正確的函數,如下所示:
return conversionFunctionArray[yards, meters](someValue);
數組將像這樣初始化:
conversionFunction[yards][meters]=yardsToMeters(somevalue);
conversionFunction[meters][yards]=metersToYards(somevalue);
conversionFunction[yards][feet]=yardsToFeet...
...
關於函數指針和數組,我缺少什么?
根據問題中的零碎指示,這是此問題的“ 最小完整可驗證示例” 。
#include <stdio.h>
double f1( double );
double f2( double );
double f3( double );
int main( void )
{
// testing a single function pointer
double (*ptr1)(double) = f1;
printf( "%.0lf\n\n", (*ptr1)(5) );
// testing an array of function pointers with an initializer list
double (*array[3])(double) = { f1, f2, f3 };
for ( int i = 0; i < 3; i++ )
printf( "%.0lf\n", (*array[i])(6) );
printf( "\n" );
// testing an array of function pointers that is initialized by assignments
double (*otherArray[3])(double);
otherArray[0] = f1;
otherArray[1] = f2;
otherArray[2] = f3;
for ( int i = 0; i < 3; i++ )
printf( "%.0lf\n", (*otherArray[i])(7) );
printf( "\n" );
}
double f1( double x ) { return 10+x; }
double f2( double x ) { return 20+x; }
double f3( double x ) { return 30+x; }
請注意,此代碼編譯時不會出現任何錯誤或警告,並會產生預期的輸出。 再次說明為什么調試問題必須包含“ 最小完整可驗證示例” 。
一個明顯的問題是您尚未實際定義任何功能function1
等。
為了看到這一點,讓我們僅使用一個函數和僅包含一個元素的數組來完成此操作。 將其放在頂層:
double function1(double);
double (*aFunctionPointer)(double)=function1;
double (*anArrayOfFunctionPointers[1])(double)={function1};
double (*anotherArrayOfFunctionPointers[1])(double);
在實際的可執行代碼中,執行以下操作:
anotherArrayOfFunctionPointers[0]=function1; // error
那是一個錯誤。 但是,現在讓我們實際定義 function1
,如下所示:
double function1(double f) {return 3.0;};
double (*aFunctionPointer)(double)=function1;
double (*anArrayOfFunctionPointers[1])(double)={function1};
double (*anotherArrayOfFunctionPointers[1])(double);
現在讓我們嘗試相同的代碼:
anotherArrayOfFunctionPointers[0]=function1;
沒錯 不同之處在於,現在我們實際上有一個要指向的function1
。 使用您的代碼,那里就沒有了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.