int arr[4];You can access the elements of the array using array indexing, like "arr[2]". You can also point to a given array element using the address-of operator:
int arr[4];The pointer is accessing arr[2], so this prints:
arr[0]=0; arr[1]=1; arr[2]=20; arr[3]=300;
int *p=&arr[2]; /* point to arr[2] */
*p=999;
for (int i=0;i<4;i++) cout<<"arr["<<i<<"]="<<arr[i]<<"\n";
arr[0]=0You can move the pointer p down so it points to arr[3] with:
arr[1]=1
arr[2]=999
arr[3]=300
p++;(Try this in NetRun now!)
p=p+1;
You can even move the pointer backwards, pointing to arr[1]:
int arr[4];
arr[0]=0; arr[1]=1; arr[2]=20; arr[3]=300;
int *p=&arr[2]; /* point to arr[2] */
p=p-1; /* move from arr[2] to arr[1] */
*p=999;
for (int i=0;i<4;i++) cout<<"arr["<<i<<"]="<<arr[i]<<"\n";
This prints
arr[0]=0
arr[1]=999
arr[2]=20
arr[3]=300
In fact, normal array indexing can be written using pointer
arithmetic. We treat the array as a pointer, move down by "i"
integers, and access the data there:
arr[i]=999;In fact, because addition is commutative, this is exactly the same as:
*(arr+i)=999;
*(i+arr)=999;This works fine, but of course it looks extremely weird! (Try this in NetRun now!)
i[arr]=999;
In general, all of the following operations work fine on pointers:
const char *arr="howdyX";The more typical way to write this loop would be to continue the loop until we hit the 0 character (ASCII nul byte) at the end of the string:
for (const char *p=arr;*p!='X';p++)
cout<<*p<<"\n";
const char *arr="howdy";Here's a program that loops over the elements of an integer array using a pointer. Each time through the loop, "p++" advances the pointer to the next element. The loop test, "p!=end", compares our pointer to "end", which points to the end of the array.
for (const char *p=arr;*p!=0;p++)
cout<<*p<<"\n";
int arr[4];
arr[0]=0; arr[1]=1; arr[2]=20; arr[3]=300;
int *end=&arr[4]; // one-past-last element of array
for (int *p=&arr[0];p!=end;p++)
cout<<"memory at "<<p<<" = "<<*p<<"\n";