Function Pointers in C

来源: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.

扫描二维码关注公众号,回复: 5008996 查看本文章

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).

猜你喜欢

转载自www.cnblogs.com/yibeimingyue/p/10298451.html