A detailed summary of the relationship between one dimensional arrays and Pointers in C++

  • 2020-04-02 01:25:16
  • OfStack

For int a[10];
A represents the address of the first element of the array, namely &a[0];

If you make the pointer p to point to the first element of the array, you can operate:
Int * p = a;
or
Int * p = & a [0];

So p++ is pointing to the first element in the array, which is a[1];
In this case, *p is the value put in a[1].
At this point, a [I] = [I] = p * (a + I) = * (p + I)

Here's an example;
Direct output with 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;
}

It's going to be output by *(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;
}

It's going to be *(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;
}

About * p++
Since ++ and * have the same priority and the combination direction is from right to left, it is equivalent to *(p++). Function: first get the value of the variable that p points to (that is, *p), and then add 1 to the value that points to 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;
}

Is equivalent to

#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++ is the same thing as *(p++); And then *(++p) means you make p+1, and then you take *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;
}

Running the above program will output values a[2] to a[11], where a[11] is not defined.


Related articles: