< Previous | Contents | Next >

Using an Array Name as a Constant Pointer

Because an array name is a constant pointer to the first element of the array, you can dereference the name to get at the first element. Thats what I do after I create an array of high scores, called highScores.

cout << *highScores << endl;

I dereference highScores to access the first element in the array and send it to

cout. As a result, 5000 is displayed.

You can randomly access array elements using an array name as a pointer through simple addition. All you have to do is add the position number of the element you want to access to the pointer before you dereference it. This is simpler than it sounds. For example, I next access the score at position 1 in highScores with the following line, which displays 3500.

cout << *(highScores + 1) << endl;

In the preceding code, *(highScores + 1) is equivalent to highScores[1]. Both return the element in position 1 of highScores.

Next, I access the score at position 2 in highScores with the following line, which displays 2700.

cout << *(highScores + 2) << endl;

Understanding the Relationship between Pointers and Arrays 247


In the preceding code, *(highScores + 2) is equivalent to highScores[2]. Both return the element in position 2 of highScores. In general, you can write arrayName[i] as *(arrayName + i), where arrayName is the name of an array.