- The indirection operator returns the value at the address stored in a pointer. The
address-of operator (&) returns the memory address of the variable. - 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 ........................................................................................................
- 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. - unsigned short pAge = &yourAge;
3.pAge = 50; - 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. - 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