While the pointer may be a variable, it also may be a constant. Indeed, in the previous chapter we actually discussed a constant pointer: the name of an array. As you may recall from Chapter 10, the value of the name of an array is the base address of the array, which also is the address of the first element of an array. Thus, in the following program, both testScore and &testScore[0] have the same value. #include <iostream> using namespace std; const int MAX = 3; int main () The resulting output is The address of the array using testScore is 0012FECC Similarly, if you dereference the name of an array, its value is the same as the value of the first element of the array. Therefore, in the preceding program, both *testScore and testScore[0] have the same value. However, you cannot change the value of the name of the array. For example, a statement such as testScore++ would result in a compiler error, the error message being “++ needs l-value.”As you may recall from Chapter 10, the term l-value refers to the value to the left of the assignment operator. This error message is another way of saying you can’t increment a constant because that would be changing the value of a constant after you declare it. Pointer ArithmeticThe value of a pointer, even though it is an address, is a numeric value. Therefore, you can perform arithmetic operations on a pointer just as you can a numeric value. Using a Variable Pointer to Point to an ArrayPointer arithmetic is done often with arrays. However, since you cannot change the value of the name of an array, it being a constant pointer, you first should declare a variable pointer and then assign it to the address of an array. So, we begin with an established point of reference, let’s start with the following program, which outputs the address and value at each element of an array using the name of the array: #include <iostream>> using namespace std; const int MAX = 3; int main () The resulting output is The address of index 0 of the array is 0012FECC This program used the name of the array, testScore, to access, by index, each element of the array. The name of the array is a constant pointer. The following program modifies the previous program by using a variable pointer, iPtr, to access by index each element of the array. #include <iostream>> using namespace std; const int MAX = 3; int main () The following statement in this program sets the variable pointer iPtr to point to the same address as the array name testScore: int* iPtr = testScore; The array name is not preceded with the address operator (&) because the array name already is an address, namely, the base address of the array. Therefore, after this assignment, iPtr and testScore both point to the beginning of the array. Accordingly, as shown in Figure 11-2, iPtr[2] and testScore[2] have the same value.
blog comments powered by Disqus |
|
|
|
|
|
|
|