C++一维数组和指针的关系总结

原博客地址:https://blog.csdn.net/qsyzb/article/details/9449355


****a[i]=p[i]=*(a+i)=*(p+i)是错误的


对于数组int a[10];

a表示数组的第一个元素的地址,即&a[0];

如果使指针p,指向数组的首元素,可以进行操作:

int * p=a;

或者

int *p=&a[0];

那么p++,是指向数组中的先一个元素,即a[1];

此时*p则是a[1]中所放的值。

此时,a[i]=p[i]=*(a+i)=*(p+i)

下面举一个例子;

直接用a[i]来输出

[cpp]  view plain  copy
  1. #include<iostream>  
  2. using namespace std;  
  3. int main(){  
  4.     int a[10]={1,2,3,4,5,6,7,8,9,10};  
  5.     cout<<"Please input 10 intergers: "<<endl;  
  6.     int i=0;  
  7.     for(i=0;i<10;i++)  
  8.     cout<<a[i]<<" ";  
  9.     cout<<endl;  
  10.     return 0;  
  11. }  

用*(a+i)来输出

[cpp]  view plain  copy
  1. #include<iostream>  
  2. using namespace std;  
  3. int main(){  
  4.     int a[10]={1,2,3,4,5,6,7,8,9,10};  
  5.     cout<<"Please input 10 intergers: "<<endl;  
  6.     int i=0;  
  7.     for(i=0;i<10;i++)  
  8.     cout<<*(a+i)<<" ";  
  9.     cout<<endl;  
  10.     return 0;  
  11. }  

用*(p+i)来输出

[cpp]  view plain  copy
  1. #include<iostream>  
  2. using namespace std;  
  3. int main(){  
  4.     int a[10]={1,2,3,4,5,6,7,8,9,10};  
  5.     cout<<"Please input 10 intergers: "<<endl;  
  6.     int i=0;  
  7.     int * p=a;  
  8.     for(i=0;i<10;i++)  
  9.     cout<<*(p+i)<<" ";  
  10.     cout<<endl;  
  11.     return 0;  
  12. }  

关于*p++

由于++和*的优先级相同,结合方向是自右而左,因此它等价于*(p++)。作用是:先得到p指向的变量的值(即*p),然后再使指向p的值加1.

[cpp]  view plain  copy
  1. #include<iostream>  
  2. using namespace std;  
  3. int main(){  
  4.     int a[10]={1,2,3,4,5,6,7,8,9,10};  
  5.     cout<<"Please input 10 intergers: "<<endl;  
  6.     int i=0;  
  7.     int * p=a;  
  8.     while(p<a+10){  
  9.         cout<<*p++<<"\t";  
  10.     }  
  11.     cout<<endl;  
  12.     return 0;  
  13. }  

等价于

[cpp]  view plain  copy
  1. #include<iostream>  
  2. using namespace std;  
  3. int main(){  
  4.     int a[10]={1,2,3,4,5,6,7,8,9,10};  
  5.     cout<<"Please input 10 intergers: "<<endl;  
  6.     int i=0;  
  7.     int * p=a;  
  8.     while(p<a+10){  
  9.         cout<<*p<<"\t";  
  10.         p++;  
  11.     }  
  12.     cout<<endl;  
  13.     return 0;  
  14. }  

*p++等价于*(p++);而*(++p)表示先使p+1,再取*p.

[cpp]  view plain  copy
  1. #include<iostream>  
  2. using namespace std;  
  3. int main(){  
  4.     int a[10]={1,2,3,4,5,6,7,8,9,10};  
  5.     cout<<"Please input 10 intergers: "<<endl;  
  6.     int i=0;  
  7.     int * p=a;  
  8.     while(p<a+10){  
  9.         cout<<*(++p)<<"\t";  
  10.     }  
  11.     cout<<endl;  
  12.     return 0;  
  13. }  

运行上面的程序,结果将输出a[2]到a[11]的值,其中a[11]并没有定义。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值