1. Indexing a Pointer
As you have just seen, it is possible to access an array by using pointer arithmetic. What you might find surprising is that the reverse is also true. In C++, it is possible to index a pointer as if it were an array. This further illustrates the close relationship between pointers and arrays. Here is an example that indexes a pointer.
// POINTER5.cpp : Defines the entry point for the console application.
using namespace std;
int _tmain(int argc, _TCHAR* argv)
char str = "hello tom";
p = str; // put address of str into p
// now, index p like an array
for(i=0; p[i]; i++) p[i] = toupper(p[i]);
cout << p; // display the string
The program displays
Here is how it works. First the program loads the string str with "hello tom". It then assigns the address of the beginning of str to p. Next, using toupper( ), it converts each character in the string to uppercase by indexing p. Remember, the expression p[i] is functionally identical to *(p+i).