0. 指针类型
- 定义变量
char *name = "wxx";
- 作为形参类型
void demo(int *p); int main() { int nums[] = {1, 3, 5}; demo(nums); printf("%i\n", nums[0]); return 0; } void demo(int *p) { p[0] = 88; }
- 作为返回值
char *demo(void); int main() { char *nameStr = demo(); printf("%s\n", nameStr); return 0; } char *demo(void) { char *str = "wxx"; return str; }
1. 指针和函数
- 概念:通过
指针
保存
函数实现地址
格式:返回值类型 (*变量名称)(形参类型, ...); void eatApple() { printf("吃苹果\n"); } int getMoney() { return 100; } void eatFood(char *food) { printf("吃%s\n", food); } int sum(int v1, int v2) { return v1 + v2; } int main() { void (*eatAppleP)(void) = eatApple; eatAppleP(); int (*getMoneyP)(void) = getMoney; printf("%i\n", getMoneyP()); void (*eatFoodP)(char *) = eatFood; eatFoodP("美食"); int (*sumP)(int, int) = sum; printf("%i\n", sumP(10, 20)); return 0; }
- 操作
- 通过
指针
来调用
函数int sum(int, int); int main() { int (*sump)(int , int) = NULL; sump = sum; int num = sump(10, 10); printf("%i\n", num); } int sum(int v1, int v2) { return v1 + v2; }
- 通过
指针
来传递
函数int sum(int, int); int minus(int, int); int demo(int, int, int (*p)(int, int)); int main(int argc, const char * argv[]) { printf("%i\n", demo(30, 10, minus)); return 0; } int sum(int v1, int v2) { return v1 + v2; } int minus(int v1, int v2) { return v1 - v2; } int demo(int v1, int v2, int (*p)(int, int)) { return p(v1, v2); }
- 通过
网友评论