一、指针作为函数的参数
(1) 交换两个值
void swap(int *xp,int *yp){
int t;
t=*xp;
*xp=*yp;
*yp=t;
}
swap(&x,&y);
(2)利用指针参数带会函数中的多个值max、min、aver
double favor(int s[],int n,int*max,int*min){
double aver=s[0];
*max=*min=s[0];
for(int i=1;i<n;i++){
aver+=s[i];
if(s[i]>*max){
*max=s[i];
}
if(s[i]<*min){
*min=s[i];
}
}
return aver/n;
}
int main(){
int a[5]={1,2,3,4,5},max,min;
double aver;
aver=favor(a,5,&max,&min);
cout<<max<<" "<<min<<" "<<aver;
}
二、返回指针的函数(删除空格)
char*noblank(char*str){
while(*str==' '){
str++;
}
return str;
}
int main(){
char*s1=" using";
char*s2=noblank(s1);
cout<<s2<<endl;
cout<<"using";
return 0;
}
三、数组与指针
1、一维数组
数组名代表数组的首地址(即数组第一个元素的地址)
int a[10],*p=a;
int a[10],*p=&a[0];
上下两种是等价的
2、二维数组
用指针在二维数组中寻找最大值
int a[3][4]={{1,2,3,4},{4,5,6,7},{7,8,9,10}};
int*p,max=a[0][0];
for(p=&a[0][0];p<&a[0][0]+12;p++){
if(*p>max){
max=*p;
}
}
cout<<"max="<<max<<endl;
3、利用*p[M]指向一行元素,M为列数
举例:用来按列输出二维数组的元素
int a[3][4]={{1,2,3,4},{4,5,6,7},{7,8,9,10}};
int (*p)[4];
for(p=a;p<a+3;p++){
for(int j=0;j<4;j++){
cout<<*(*p+j)<<"\t";
}
cout<<endl;
4、字符串指针是字符串第一个字符的地址
char*str;
str="Hello";
四、指针的关系运算
1、关系运算(讲指针看做整数,可比较大小)
double x[5]={1,2,4,5,7},*p;
for{p=x;p<x+5;p++){
cout<<*p<<"\t";
}
2数组元素表示的不同形式
int main(){
int a[10]={1,2,3,4,5,6,7,8,9,0},*p=a;
cout<<*(a+2)<<endl;
cout<<a[2]<<endl;
cout<<*(p+2)<<endl;
cout<<p[2];
}
五、指针与结构体
1、定义指向结构体变量的指针
Date d = {2015, 4, 8};
Date* p = &d;
2、使用结构体指针访问结构变量中的成员
struct Date{
int year;
int month;
int day;
};
int main(){
Date d={2015,4,8},*p=&d;
cout<<(*p).year<<"-"<<(*p).month<<"-"<<(*p).day<<endl;
cout<<p->year<<"-"<<p->month<<"-"<<p->day<<endl;
return 0;
}
六、动态数组
如何定义n个元素的一维数组?
动态申请:new运算符
1、动态申请单个变量
指针变量=new类型
double*p;
p=new double(100.0);
2、动态申请数组
指针变量=new 类型【元素个数】
举例:动态申请存放八十个字符的数组
char*p;
p=new char[80];
3、举例:动态创建n个元素的一维整型数组
int n,*p;
cout<<"请输入n值:";
cin>>n;
p=new int[n];
if(p==NULL){
cout<<"空间申请失败";
return 1;
}
cout<<"请输入n个数:";
for(int i=0;i<n;i++){
cin>>p[i];
}
七、大量例子
1、给三个数排序
void swap(int*px,int*py){
int temp;
temp=*px;
*px=*py;
*py=temp;
}
int main(){
int a,b,c;
cout<<"请输入三个数:"<<endl;
cin>>a>>b>>c;
int *pa,*pb,*pc;
pa=&a;
pb=&b;
pc=&c;
if(*pa>*pb){
swap(pa,pb);
}
if(*pa>*pc){
swap(pa,pc);
}
if(*pb>*pc){
swap(pb,pc);
}
cout<<a<<b<<c;
}
2、去掉字符串首部的空格(返回指针的函数)
char* sstr(char s[]) {
int k, j;
k = 0;
while (s[k] == ' ') {
k++;
}
j = k;
while (s[j] != '\0') {
s[j - k] = s[j];
j++;
}
s[j - k] ='\0';
return s;
}
int main() {
char name[20];
cin.getline(name, 19);
cout << sstr(name) << endl;
return 0;
}
3、计算圆的周长和面积(利用指针返回多个值)
void circle(double cr,double *cc,double *cs){
*cc=2*3.14157*cr;
*cs=3.14157*cr*cr;
}
int main() {
double r,c,s;
cin>>r;
circle(r,&c,&s);
cout<<r<<endl<<c<<endl<<s;
return 0;
}
4、梯形法求定积分(指向函数的指针)
double integral(double a,double b,double(*fun)(double),int n){
double h=(b-a)/n;
double sum=((*fun)(a)+(*fun)(b))/2;
for(int i=1;i<n;i++){
sum+=(*fun)(a+i*h);
}
sum*=h;
return sum;
}
double sinx(double x){
return sin(x);
}
int main(){
double s=integral(0,3.1415926/2,sinx,1000);
cout<<s;
}