Indexing a Pointer

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.

#include "stdafx.h"
#include <iostream>
#include <cctype>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
            char str[20] = "hello tom";
            char *p;
            int i;
            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
            return 0;

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).
Share on Google Plus