c语言函数指针

函数指针是指向函数的指针变量。

函数指针是指针变量,该指针变量指向函数。

函数指针的用途:调用函数,做函数的参数。

调用函数

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
#include <stdio.h>

int max(int, int);
int min(int, int);

int main() {
int num1 = 1, num2 = 2, num3;
int (*func)(int, int);//函数指针,变量名称func,变量类型int (int, int) *

func = max;
num3 = (*func)(num1, num2);
printf("max:%d\n", num3);
func = min;
num3 = (*func)(num1, num2);
printf("min:%d\n", num3);
return 0;
}

int max(int num1, int num2) {
return num1 > num2 ? num1 : num2;
}

int min(int num1, int num2) {
return num1 < num2 ? num1 : num2;
}

做函数的参数

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
28
29
30
31
32
33
34
35
36
37
#include <stdlib.h>
#include <iostream>
#include <algorithm>

int up(const void *, const void *);
int down(const void *, const void *);

int main() {
int arr[] = {4, 3, 1, 2, 5};
int (*func)(const void *num1, const void *num2);//函数指针,变量名称func,变量类型int (const void *, const void *) *
//func = [](const void *num1, const void *num2) {
// return *(int*)num1 - *(int*)num2;
//};
func = up;
qsort(arr, 5, sizeof(int), func);
for(const auto &element : arr) {
std::cout << element << " ";
}
std::cout << std::endl;
//func = [](const void *num1, const void *num2) {
// return *(int*)num2 - *(int*)num1;
//};
func = down;
qsort(arr, 5, sizeof(int), func);
for(const auto &element : arr) {
std::cout << element << " ";
}
return 0;
}

int up(const void *num1, const void *num2) {
return *(int*)num1 - *(int*)num2;
}

int down(const void *num1, const void *num2) {
return *(int*)num2 - *(int*)num1;
}

Windows中的函数指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
typedef LRESULT (CALLBACK* WNDPROC)(HWND, UINT, WPARAM, LPARAM);
typedef VOID (CALLBACK* TIMERPROC)(HWND, UINT, UINT_PTR, DWORD);
typedef BOOL (CALLBACK* GRAYSTRINGPROC)(HDC, LPARAM, int);
typedef BOOL (CALLBACK* WNDENUMPROC)(HWND, LPARAM);
typedef LRESULT (CALLBACK* HOOKPROC)(int code, WPARAM wParam, LPARAM lParam);
typedef VOID (CALLBACK* SENDASYNCPROC)(HWND, UINT, ULONG_PTR, LRESULT);

typedef BOOL (CALLBACK* PROPENUMPROCA)(HWND, LPCSTR, HANDLE);
typedef BOOL (CALLBACK* PROPENUMPROCW)(HWND, LPCWSTR, HANDLE);

typedef BOOL (CALLBACK* PROPENUMPROCEXA)(HWND, LPSTR, HANDLE, ULONG_PTR);
typedef BOOL (CALLBACK* PROPENUMPROCEXW)(HWND, LPWSTR, HANDLE, ULONG_PTR);

typedef int (CALLBACK* EDITWORDBREAKPROCA)(LPSTR lpch, int ichCurrent, int cch, int code);
typedef int (CALLBACK* EDITWORDBREAKPROCW)(LPWSTR lpch, int ichCurrent, int cch, int code);

typedef BOOL (CALLBACK* NAMEENUMPROCA)(LPSTR, LPARAM);
typedef BOOL (CALLBACK* NAMEENUMPROCW)(LPWSTR, LPARAM);