|
|
|
|
|
|
|
Notice that the logical NOT operator can be used to test for the null pointer: |
|
|
|
|
|
|
|
|
if ( !ptr )
DoSomething(); |
|
|
|
|
|
|
|
|
Some people find this notation confusing because ptr is a pointer expression, not a Boolean expression. We prefer to phrase the test this way for clarity: |
|
|
|
|
|
|
|
|
if (ptr == NULL)
DoSomething() ; |
|
|
|
|
|
|
|
|
When looking at the table above, it is important to keep in mind that the operations listed are operations on pointers, not on the pointed-to variables. For example, if intPtr1 and intPtr2 are variables of type int*, the test |
|
|
|
|
|
|
|
|
compares the pointers, not what they point to. In other words, we are comparing memory addresses, not ints. To compare the integers that intPtr1 and intPtr2 point to, we would need to write |
|
|
|
|
|
|
|
|
if (*intPtr1 == *intPtr2) |
|
|
|
|
|
|
|
|
In addition to the operators we have listed in the table, the following C++ operators may be applied to pointers: ++, --, +, -, +=, and -=. These operators perform arithmetic on pointers that point to arrays. For example, the expression ptr++ causes ptr to point to the next element of the array, regardless of the size in bytes of each array element. And the expression ptr + 5 accesses the array element that is five elements beyond the one currently pointed to by ptr. We'll say no more about these operators or about pointer arithmetic; the topic of pointer arithmetic is off the main track of what we want to emphasize in this chapter. Instead, we proceed now to explore one of the most important uses of pointers: the creation of dynamic data. |
|
|
|
|
|
|
|
|
In Chapter 8, we described two categories of program data in C++: static data and automatic data. Any global variable is static, as is any local variable explicitly declared as static. The lifetime of a static variable is the lifetime of |
|
|
|
|
|