adjusting section 2

This commit is contained in:
Jidong Xiao
2023-09-18 22:00:18 -04:00
parent 604718ac28
commit 1c0cdec736

View File

@@ -29,7 +29,8 @@ Dynamic memory is:
<table> <table>
<tr> <tr>
<td> <td>
<pre>
<pre>
int * p = new int; int * p = new int;
*p = 17; *p = 17;
cout << *p << endl; cout << *p << endl;
@@ -44,25 +45,38 @@ p = temp;
cout << *p << " " << *q << endl; cout << *p << " " << *q << endl;
delete p; delete p;
delete q; delete q;
</pre> </pre>
</td> </td>
<td><img src="heap.png" alt="heap"</td> <td><img src="heap.png" alt="heap"</td>
</tr> </tr>
</table> </table>
<!--[alt text](heap.png "heap")--> <!--[alt text](heap.png "heap")-->
- The expression new int asks the system for a new chunk of memory that is large enough to hold an integer - The expression *new int* asks the system for a new chunk of memory that is large enough to hold an integer
and returns the address of that memory. Therefore, the statement int * p = new int; allocates memory and returns the address of that memory. Therefore, the statement
from the heap and stores its address in the pointer variable p.
- The statement delete p; takes the integer memory pointed by p and returns it to the system for re-use. ```cpp
- This memory is allocated from and returned to a special area of memory called the heap. By contrast, local int * p = new int;
variables and function parameters are placed on the stack as discussed last lecture. ```
- In between the new and delete statements, the memory is treated just like memory for an ordinary variable,
allocates memory from the heap and stores its address in the pointer variable *p*.
- The statement
```cpp
delete p;
```
takes the integer memory pointed by *p* and returns it to the system for re-use.
- This memory is allocated from and returned to a special area of memory called the **heap**. By contrast, local
variables and function parameters are placed on the stack.
- In between the *new* and *delete* statements, the memory is treated just like memory for an ordinary variable,
except the only way to access it is through pointers. Hence, the manipulation of pointer variables and values is except the only way to access it is through pointers. Hence, the manipulation of pointer variables and values is
similar to the examples covered in Lecture 5 except that there is no explicitly named variable for that memory similar to the examples covered in the pointers lecture except that there is no explicitly named variable for that memory
other than the pointer variable. other than the pointer variable.
- Dynamic allocation of primitives like ints and doubles is not very interesting or significant. Whats more - Dynamic allocation of primitives like ints and doubles is not very interesting or significant. Whats more important is dynamic allocation of arrays and class objects.
important is dynamic allocation of arrays and objects.
## 6.3 Exercises ## 6.3 Exercises