zoukankan      html  css  js  c++  java
  • 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 ", (*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).

  • 相关阅读:
    repeater 设置分页
    table表格合并
    repeater分页
    http错误500.19 错误代码 0x80070021
    asp文件上传和下载
    asp:Repeater控件使用
    vs2013标签
    "Uncaught SyntaxError: Unexpected token <"错误完美解决
    监控系统说明文档
    限制input输入类型(多种方法实现)
  • 原文地址:https://www.cnblogs.com/yibeimingyue/p/10298451.html
Copyright © 2011-2022 走看看