Sams Teach Yourself C++ in 21 Days

(singke) #1

248 Day 8



  1. pIntwas assigned the value 20 —or 00 14in hexadecimal notation. Because pIntstill
    pointed to the same address, the first two bytes of pLongwere overwritten, leaving
    00 14 00 01.

  2. The value at pLongwas printed, reversing the bytes back to their correct order of 00
    01 00 14, which was translated into the DOS value of 65556.


FAQ
What is the difference between a null pointer and a stray pointer?
Answer:When you delete a pointer, you tell the compiler to free the memory, but the
pointer itself continues to exist. It is now a stray pointer.
When you then write myPtr = 0;you change it from being a stray pointer to being a
null pointer.
Normally, if you delete a pointer and then delete it again, your program is undefined.
That is, anything might happen—if you are lucky, the program will crash. If you delete a
null pointer, nothing happens; it is safe.
Using a stray ora null pointer (for example, writing myPtr = 5;) is illegal, and it might
crash. If the pointer is null, it willcrash, another benefit of null over stray. Predictable
crashes are preferred because they are easier to debug.

Using constPointers ..........................................................................................


You can use the keyword constfor pointers before the type, after the type, or in both
places. For example, all the following are legal declarations:
const int * pOne;
int * const pTwo;
const int * const pThree;
Each of these, however, does something different:


  • pOneis a pointer to a constant integer. The value that is pointed to can’t be
    changed.

  • pTwois a constant pointer to an integer. The integer can be changed, but pTwocan’t
    point to anything else.

  • pThreeis a constant pointer to a constant integer. The value that is pointed to can’t
    be changed, and pThreecan’t be changed to point to anything else.

Free download pdf