![]() |
Data Abstraction and Problem Solving with C++Walls and Mirrorsby Frank M. Carrano |
![]() |
c04p181.cppGo to the documentation of this file.00001 00016 int *p, *q; 00017 00018 p = new int; // Allocate a cell of type int. 00019 00020 *p = 1; // Assign a value to the new cell. 00021 00022 q = new int; // Allocate a cell of type int. 00023 00024 *q = 2; // Assign a value to the new cell. 00025 00026 cout << *p << " " // Output line contains: 1 2 00027 << *q << endl; // These values are in the 00028 // cells to which p and q point. 00029 00030 *p = *q + 3; // The value in the cell to which 00031 // q points, 2 in this case, and 3 00032 // are added together. The result is 00033 // assigned to the cell to which 00034 // p points. 00035 00036 cout << *p << " " // Output line contains: 5 2 00037 << *q << endl; 00038 00039 p = q; // p now points to the same cell as q. 00040 // The cell p formerly pointed to is 00041 // lost; it cannot be referenced. 00042 00043 cout << *p << " " // Output line contains: 2 2 00044 << *q << endl; 00045 00046 *p = 7; // The cell to which p points (which 00047 // is also the cell to which q points) 00048 // now contains the value 7. 00049 00050 cout << *p << " " // Output line contains: 7 7 00051 << *q << endl; 00052 00053 p = new int; // This changes what p points to, 00054 // but not what q points to. 00055 00056 delete p; // Return to the system the cell to 00057 // which p points. 00058 00059 p = NULL; // Set p to NULL, a good practice 00060 // following delete. 00061 00062 q = NULL; // The cell to which q previously 00063 // pointed is now lost. You cannot 00064 // reference it. |