adjusting section 2
This commit is contained in:
@@ -29,7 +29,8 @@ Dynamic memory is:
|
||||
<table>
|
||||
<tr>
|
||||
<td>
|
||||
<pre>
|
||||
|
||||
<pre>
|
||||
int * p = new int;
|
||||
*p = 17;
|
||||
cout << *p << endl;
|
||||
@@ -44,25 +45,38 @@ p = temp;
|
||||
cout << *p << " " << *q << endl;
|
||||
delete p;
|
||||
delete q;
|
||||
</pre>
|
||||
</pre>
|
||||
|
||||
</td>
|
||||
<td><img src="heap.png" alt="heap"</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<!--[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
|
||||
and returns the address of that memory. Therefore, the statement int * p = new int; allocates memory
|
||||
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.
|
||||
- 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 as discussed last lecture.
|
||||
- In between the new and delete statements, the memory is treated just like memory for an ordinary variable,
|
||||
- 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
|
||||
|
||||
```cpp
|
||||
int * p = new int;
|
||||
```
|
||||
|
||||
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
|
||||
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.
|
||||
- Dynamic allocation of primitives like ints and doubles is not very interesting or significant. What’s more
|
||||
important is dynamic allocation of arrays and objects.
|
||||
- Dynamic allocation of primitives like ints and doubles is not very interesting or significant. What’s more important is dynamic allocation of arrays and class objects.
|
||||
|
||||
## 6.3 Exercises
|
||||
|
||||
|
||||
Reference in New Issue
Block a user