1 Ponter function

Function pointer is a pointer in c, and it returns a pointer of some type. For instance, its declaration follows

1
2
int *f(int x, int y);

Let’s give a code demo to show function pointer.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
int *add2Num() {
    int x = 10, y = 20;
    static int out[3] = {0};
    out[0] = 10; out[1] = y; out[2] = x + y;
    return out;
}

int main() {
    int *p = NULL;
    p = add2Num();
    printf("%d\n", *(p+1));
    return 0;
}

Output 20

2 Function pointer

Actually, function pointer is a pointer, and it points at a function. Its declaration is given by

1
int (*func) (int x, int y);

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// Give a function.
int max( int x, int y ) {
    return x > y ? x : y;
}

// Declaration of a function pointer.
int (*func) (int x, int y );

int main() {
	// Let this pointer be the address of `max` function.
    func = max;
    printf("%d\n", (*func)(10, 20));
    return 0;
}

output 20

3 Set function pointers as the parameters of a function

Formal parameter: type (*func) (); Calling the function: ... = func();

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

int max( int x, int y ) {
    return x > y ? x : y;
}

int getRandomValue() {
    return rand();
}

void printValue( int *array, int size, int (*p)() ) {
    srand((unsigned) (time(NULL)));
    int i = 0;
    for ( i = 0; i < size; i ++ ) {
        *(array+i) = p();
        printf("%d\n", *(array+i));
    }
}

int main() {
    int arr[10] = {0};
    printValue(arr, 10, getRandomValue);
    return 0;
}