原博客地址: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]来输出
- #include<iostream>
- using namespace std;
- int main(){
- int a[10]={1,2,3,4,5,6,7,8,9,10};
- cout<<"Please input 10 intergers: "<<endl;
- int i=0;
- for(i=0;i<10;i++)
- cout<<a[i]<<" ";
- cout<<endl;
- return 0;
- }
用*(a+i)来输出
- #include<iostream>
- using namespace std;
- int main(){
- int a[10]={1,2,3,4,5,6,7,8,9,10};
- cout<<"Please input 10 intergers: "<<endl;
- int i=0;
- for(i=0;i<10;i++)
- cout<<*(a+i)<<" ";
- cout<<endl;
- return 0;
- }
用*(p+i)来输出
- #include<iostream>
- using namespace std;
- int main(){
- int a[10]={1,2,3,4,5,6,7,8,9,10};
- cout<<"Please input 10 intergers: "<<endl;
- int i=0;
- int * p=a;
- for(i=0;i<10;i++)
- cout<<*(p+i)<<" ";
- cout<<endl;
- return 0;
- }
关于*p++
由于++和*的优先级相同,结合方向是自右而左,因此它等价于*(p++)。作用是:先得到p指向的变量的值(即*p),然后再使指向p的值加1.
- #include<iostream>
- using namespace std;
- int main(){
- int a[10]={1,2,3,4,5,6,7,8,9,10};
- cout<<"Please input 10 intergers: "<<endl;
- int i=0;
- int * p=a;
- while(p<a+10){
- cout<<*p++<<"\t";
- }
- cout<<endl;
- return 0;
- }
等价于
- #include<iostream>
- using namespace std;
- int main(){
- int a[10]={1,2,3,4,5,6,7,8,9,10};
- cout<<"Please input 10 intergers: "<<endl;
- int i=0;
- int * p=a;
- while(p<a+10){
- cout<<*p<<"\t";
- p++;
- }
- cout<<endl;
- return 0;
- }
*p++等价于*(p++);而*(++p)表示先使p+1,再取*p.
- #include<iostream>
- using namespace std;
- int main(){
- int a[10]={1,2,3,4,5,6,7,8,9,10};
- cout<<"Please input 10 intergers: "<<endl;
- int i=0;
- int * p=a;
- while(p<a+10){
- cout<<*(++p)<<"\t";
- }
- cout<<endl;
- return 0;
- }
运行上面的程序,结果将输出a[2]到a[11]的值,其中a[11]并没有定义。