In Xcode 7.2.1, I declare 3 C functions
double function1(double);
double function2(double);
double function3(double);
Now I declare a pointer to a function and define it.
double (*aFunctionPointer)(double)=function1;
No errors, as expected.
Now I declare an array of function pointers and fill it with my 3 functions.
double (*anArrayOfFunctionPointers[3])(double)={function1, function2, function3};
Again, no errors.
Now I define an array of function pointers, but do not fill it.
double (*anotherArrayOfFunctionPointers[3])(double);
Again, no errors.
Now I try to assign a function to one of the array elements.
anotherArrayOfFunctionPointers[1]=function2;
This time, warnings and errors:
- Warning: Type specifier missing, defaults to int
- Error: Redefinition of 'anotherArrayOfFunctionPointers' with a different type:'int [0]' vs 'double (*[3]) (double)'
I am stumped.
The background is that I am trying to write a program to convert between various units of measure. I thought I would use a two-dimensional array containing function pointers, in order to avoid a number of very lengthy switch statements.
To make a conversion, I would call a function as follows:
result=convert(someValueToConvert,yards,meters);
and the convert function would invoke the correct function from the array like so:
return conversionFunctionArray[yards, meters](someValue);
The array would be initialized like so:
conversionFunction[yards][meters]=yardsToMeters(somevalue);
conversionFunction[meters][yards]=metersToYards(somevalue);
conversionFunction[yards][feet]=yardsToFeet...
...
What am I missing as regards function pointers and arrays?
typedefis a very useful tool when dealing with function pointers. Try something liketypedef double (*funcPtr_t)(double);to create a function pointer type, then something likefuncPtr_t funcPtrArray[3];for your array.