對於數組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; } #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; } #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; } #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"; } 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; } #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; } #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]並沒有定義。