来源:https://cs.nyu.edu/courses/spring12/CSCI-GA.3033-014/Assignment1/function_pointers.html
Function Pointers in C
Just as a variable can be declared to be a pointer to an int, a variable can also declared to be a pointer to a function (or procedure). For example, the following declares a variable v whose type is a pointer to a function that takes an int as a parameter and returns an int as a result:
int (*v)(int); That is, v is not itself a function, but rather is a variable that can point to a function.
Since v does not yet actually point to anything, it needs to be assigned a value (i.e. the address of a function). Suppose you have already defined the following function f, as follows.
int f(int x) { return x+1; }
To make v point to the function f, you simply need to assign v as follows:
v = f; To call the function that v points to (in this case f), you Could write, for example,
... (*v)(6) ...
That is, it would look like an ordinary function call, except that you would need to dereference v using * and wrap parentheses around the *v.
Putting it all together, here is a simple program:
#include int (*v)(int); int f(int x) { return x+1; } main() { v = f; printf("%d\n", (*v)(3)); } Notice that it is often convenient to use a typedef to define the function type. For example, if you write
typedef void (*MYFNPOINT)(int);
then you have defined a type MYFNPOINT. Variables of this type point to procedures that take an int as a parameter and don't return anything. For example,
MYFNPOINT w;
declares such a variable.
Of course, you can declare a struct (record) type the contains function pointers, among other things. For example,
typedef struct { int x; int (*f)(int, float); MYFNPOINT g; } THING; declares a type THING which is a structure containing an int x and two function pointers, f and g (assuming the deFinition of the MYFNPOINT type, above).
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。