c语言中函数指针用法
#include <stdio.h> #define MAX 10 void swap(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; } void fun(int *height, int *age) { int n = 10; *height = n * 10; *age = n * 2000; } int *createArray(int size) { int i; int *arr = (int *)(malloc(sizeof(int) * size)); for (i = 0; i < size; i++) { arr[i] = i * i; } return arr; } int *sumArray(int arr) { return 0; } int add(int x, int y) { return x + y; } int substract(int x, int y) { return x - y; } int multiply(int x, int y) { return x * y; } int divide(int x, int y) { return x / y; } int module(int x, int y) { return x % y; } typedef int (*operation_fun)(int, int); void main() { int num = 0; int (*ptr_add)(int, int) = add; void (*ptr_swap)(int, int) = swap; int a = 100, b = 200; int sum = ptr_add(a, b); printf("the result is %d\n", sum); ptr_swap(&a, &b); printf("before swap a is %d, b is %d\n", a, b); swap(&a, &b); printf("after swap a is %d, b is %d\n", a, b); operation_fun operations[] = { &add, &substract, &multiply, ÷, &module}; // int (*operations[])(int, int) = {add, substract, multiply, divide, module}; // int (*operations[])(int, int) = {&add, &substract, &multiply, ÷, &module}; char *arr[] = {"add", "substract", "multiply", "divide", "module"}; int result = 0; int i, j; for (i = 0; i < 5; i++) { result = operations[i](10, 20); printf("%s of two number result is %d\n", arr[i], result); } int p_height; int p_age; fun(&p_height, &p_age); printf("height is %d and age is %d\n", p_height, p_age); int c = 30; int *ptr1 = &c; int **ptr2 = &ptr1; printf("c is %d\n", c); printf("ptr1 is %d\n", *ptr1); printf("ptr2 is %d\n", **ptr2); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现