casting a pointer to a float or pointing to a function with a pointer parameter

那年仲夏 提交于 2019-12-25 19:01:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!