Pointers and Pointer Arithmetic

Dr. Lawlor, CS 202, CS, UAF

(see also Gaddis chapter 9.)

So you've got an array:
	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];
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";

(Try this in NetRun now!)

The pointer is accessing arr[2], so this prints:
arr[0]=0
arr[1]=1
arr[2]=999
arr[3]=300
You can move the pointer p down so it points to arr[3] with:
	p++;
(Try this in NetRun now!)

This does the same thing as saying:
	p=p+1;

(Try this in NetRun now!)

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";

(Try this in NetRun now!)

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;
*(arr+i)=999;
In fact, because addition is commutative, this is exactly the same as:
	*(i+arr)=999;
i[arr]=999;
This works fine, but of course it looks extremely weird!  (Try this in NetRun now!)

In general, all of the following operations work fine on pointers:

Real C++ programs often combine these features.  For example, here's a program that loops over the characters in a string, by pointing to the first character, moving the pointer to each subsequent character, and continuing until we're pointing to an 'X' character:
const char *arr="howdyX";
for (const char *p=arr;*p!='X';p++)
cout<<*p<<"\n";

(Try this in NetRun now!)

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:
const char *arr="howdy";
for (const char *p=arr;*p!=0;p++)
cout<<*p<<"\n";

(Try this in NetRun now!)

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.
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";

(Try this in NetRun now!)