Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C++ For Dummies (2004) [eng].pdf
Скачиваний:
84
Добавлен:
16.08.2013
Размер:
8.09 Mб
Скачать

Chapter 9

Taking a Second Look

at C++ Pointers

In This Chapter

Performing arithmetic operations on character pointers

Examining the relationship between pointers and arrays

Applying this relationship to increase program performance

Extending pointer operations to different pointer types

Explaining the arguments to main() in our C++ program template

C++ allows the programmer to operate on pointer variables much as she would on simple types of variables. (The concept of pointer variables is

introduced in Chapter 8.) How and why this is done along with its implica­ tions are the subjects of this chapter.

Defining Operations on Pointer Variables

Some of the same operators I cover in Chapter 3 can be applied to pointer types. This section examines the implications of applying these operators to both to pointers and to the array types (I discuss arrays in Chapter 7). Table 9-1 lists the three fundamental operations that are defined on pointers.

Table 9-1 The Three Operations Defined on Pointer Types

Operation

Result

Meaning

pointer

pointer

Calculate the address of the object

+ offset

 

integer entries from pointer

pointer - offset

pointer

The opposite of addition

 

 

 

pointer2

offset

Calculate the number of entries

- pointer1

 

between pointer2 and pointer1

126 Part II: Becoming a Functional C++ Programmer

In this case, offset is of type long. (Although not listed in Table 9-1, C++ also supports operators related to addition and subtraction, such as ++ and +=.)

The real estate memory model (which I use so effectively in Chapter 8, if I do say so myself) is useful to explain how pointer arithmetic works. Consider a city block in which all houses are numbered sequentially. The house next to 123 Main Street has the address 124 Main Street (or 122 if you go backward, like Hebrew and Arabic).

Now it’s pretty clear that the house four houses down from 123 Main Street must be 127 Main Street; thus, you can say 123 Main + 4 = 127 Main. Similarly, if I were to ask how many houses are there from 123 Main to 127 Main, the answer would be four — 127 Main - 123 Main = 4. (Just as an aside, a house is zero houses from itself: 123 Main - 123 Main = 0.)

Extending this concept one step further, it makes no sense to add 123 Main Street to 127 Main Street. In similar fashion, you can’t add two addresses, nor can you multiply an address, divide an address, square an address, or take the square root — you get the idea.

Re-examining arrays in light of pointer variables

Now return to the wonderful array for just a moment. Once again, my neigh­ borhood comes to mind. An array is just like my city block. Each element of the array corresponds to a house on that block. Here, however, the array ele­ ments are measured by the number of houses from the beginning of the block (the street corner). Say that the house right on the corner is 123 Main Street, which means that the house one house from the corner is 124 Main Street, and so on. Using array terminology, you would say cityBlock[0] is 123 Main Street, cityBlock[1] is 124 Main Street, and so on.

Take that same model back to the world of computer memory. Consider the case of an array of 32 1-byte characters called charArray. If the first byte of this array is stored at address 0x110, the array will extend over the range 0x110 through 0x12f. charArray[0] is located at address 0x110, charArray[1] is at 0x111, charArray[2] at 0x112, and so on.

Take this model one step further to the world of pointer variables. After exe­ cuting the expression

ptr = &charArray[0];

the pointer ptr contains the address 0x110. The addition of an integer offset to a pointer is defined such that the relationships shown in Table 9-2 are true. Table 9-2 also demonstrates why adding an offset n to ptr calculates the address of the nth element in charArray.

Chapter 9: Taking a Second Look at C++ Pointers 127

Table 9-2

 

Adding Offsets

Offset

Result

Is the Address of

+ 0

0x110

charArray[0]

 

 

 

+ 1

0x111

charArray[1]

 

 

 

+ 2

0x112

charArray[2]

 

 

 

...

...

...

 

 

 

+ n

0x110 + n

charArray[n]

 

 

 

The addition of an offset to a pointer is similar to applying an index to an array.

Thus, if

char* ptr = &charArray[0];

then

*(ptr + n) ← corresponds with → charArray[n]

Because * has higher precedence than addition, * ptr + n adds n to the character that ptr points to. The parentheses are needed to force the addi­ tion to occur before the indirection. The expression *(ptr + n) retrieves the character pointed at by the pointer ptr plus the offset n.

In fact, the correspondence between the two forms of expression is so strong that C++ considers array[n] nothing more than a simplified version of *(ptr + n), where ptr points to the first element in array.

array[n] -- C++ interprets as → *(&array[0] + n)

In order to complete the association, C++ takes a second shortcut. If given

char charArray[20];

charArray is defined as &charArray[0];.

That is, the name of an array without a subscript present is the address of the array itself. Thus, you can further simplify the association to

array[n] --> C++ interprets as --> *(array + n)

128 Part II: Becoming a Functional C++ Programmer

Applying operators to the address of an array

The correspondence between indexing an array and pointer arithmetic is useful.

For example, a displayArray() function used to display the contents of an array of integers can be written as follows:

// displayArray - display the members of an // array of length nSize void displayArray(int intArray[], int nSize)

{

cout << “The value of the array is:\n”;

for(int n; n < nSize; n++)

{

cout << n << “: “ << intArray[n] << “\n”;

}

cout << “\n”;

}

This version uses the array operations with which you are familiar. A pointer version of the same appears as follows:

// displayArray - display the members of an // array of length nSize void displayArray(int intArray[], int nSize)

{

cout << “The value of the array is:\n”;

int* pArray = intArray;

for(int n = 0; n < nSize; n++, pArray++)

{

cout << n << “: “ << *pArray << “\n”;

}

cout << “\n”;

}

The new displayArray() begins by creating a pointer to an integer pArray that points at the first element of intArray.

The p in the variable name indicates that the variable is a pointer, but this is just a convention, not a part of the C++ language.

The function then loops through each element of the array. On each loop, displayArray() outputs the current integer (that is, the integer pointed at by pArray) before incrementing the pointer to the next entry in intArray. displayArray() can be tested using the following version of main():