问题
I am trying to understand exactly what this line of code is, as I am learning C.
int (*f) (float *)
I know the first part is a pointer to an int named f, however the second part is what I am unsure of.
Would this be classed as a pointer to an int named f which is cast to a pointer-to-float
or
Would this be a pointer named f, pointing to a function with a pointer parameter.
Would be great if someone could help and possible explain why or the difference between the two as I am having a little trouble understanding this concept.
Thanks!
回答1:
That line declares f as a pointer to a function accepting a float * as its argument and returning an int.
The declaration may seem tricky, but it is just following the rules of C. If we wrote
int *f(float *);
Then it would seem as though f is a function returning int *. Thus, the correct precedence must be forced using parenthesis around *f.
回答2:
Here is an example of how f is defined, assigned a function pointer, and then called
#include <stdio.h>
int foo(float *real)
{
float num = *real + 0.5F;
return (int)num;
}
int main(void)
{
float number = 4.9F;
int (*f) (float *) = foo; // define f
printf("%d\n", f(&number)); // calls f
return 0;
}
Program output:
5
回答3:
If you had the declaration:
int foo(float *);
it would be clear that it was a function definition. Using (*f) instead of foo gives you a pointer to a function.
回答4:
It declares f as a pointer to a function taking a float * (a float pointer) and returning int. You can then use it like this
float array[5] = {1.0, 2.0, 3.0, 4.0, 5.0};
printf("%d\n", f(array));
来源:https://stackoverflow.com/questions/37197239/casting-a-pointer-to-a-float-or-pointing-to-a-function-with-a-pointer-parameter