指针的四种用法

来源:互联网 发布:淘宝自主品牌女装 编辑:程序博客网 时间:2024/05/16 17:51

用指针变量保存内存地址

通过指针访问它所保存的内存地址上的数据

对指针进行计算,使指针发生偏移

在函数间传递指针,达到传递数据的效果

如果指针指向某个函数,我们可以通过调用指针来调用它所指向的函数

//通过这个函数输入三十个分数,并打印出大于60分的成绩。
#include <stdio.h>
typedef void(*FUNC)(void);  //定义函数指针类型FUNC//打印函数void printpass(){puts("congratunation!"); }  void printfail() { puts("sorry!"); }void doprint(int *score,FUNC f)   //执行打印任务{printf("your score is %d.\n",*score);  //通过数据指针访问它所指向的数据if(NULL!=f)f();}int main(){const int count = 30;int scores[count];puts("please input the scores.");int *p=scores;for(int i=0;i<count;++i){scanf("%d",p);   //将输入的地址保存在p所指向的数据元素 ++p;}//让p重新指向第一个元素p=scores;FUNC pfunc=NULL; //用函数指针(FUNC f)传递函数 for(int i=0;i<count;++i){if((*p)>=60)pfunc=printpass;elsepunc=printfail;doprint(p,pfunc);++p;  } return 0;}