Sams Teach Yourself C++ in 21 Days

(singke) #1

  1. The indirection operator returns the value at the address stored in a pointer. The
    address-of operator (&) returns the memory address of the variable.

  2. The const int ptrOnedeclares that ptrOneis a pointer to a constant integer.
    The integer itself cannot be changed using this pointer.
    The int
    const ptrTwodeclares that ptrTwois a constant pointer to integer.
    After it is initialized, this pointer cannot be reassigned.


Exercises ........................................................................................................


  1. a. int pOne;declares a pointer to an integer.
    b. int vTwo;declares an integer variable.
    c. int
    pThree = &vTwo;declares a pointer to an integer and initializes it
    with the address of another variable,vTwo.

  2. unsigned short pAge = &yourAge;
    3.
    pAge = 50;

  3. The following is one possible answer:
    1: #include
    2:
    3: int main()
    4: {
    5: int theInteger;
    6: int pInteger = &theInteger;
    7:
    pInteger = 5;
    8:
    9: std::cout << β€œThe Integer: β€œ
    10: << *pInteger << std::endl;
    11:
    12: return 0;
    13: }
    5.pIntshould have been initialized. More importantly, because it was not initialized
    and was not assigned the address of any memory, it points to a random place in
    memory. Assigning a literal ( 9 ) to that random place is a dangerous bug.

  4. Presumably, the programmer meant to assign 9 to the value at pVar, which would
    be an assignment to SomeVariable. Unfortunately, 9 was assigned to be the value
    of pVarbecause the indirection operator (*) was left off. This will lead to disaster
    if pVaris used to assign a value because it is pointing to whatever is at the address
    of 9 and not at SomeVariable.


834 Appendix D

32 0672327112_app_d.qxd 11/19/04 12:30 PM Page 834

Free download pdf