The Heap
There are two memory places where variables reside: One is in the heap, a place that you may directly control, and the other is used directly when creating a variable:int x = 0;
To access the heap, you first need to create a pointer through which you will obtain the address of that variable. You may do this in two steps, or in one:
int * pointer;
pointer = new int;
OR
int * pointer = new int;
Delete Heap Variables
These heap variables (new int) take up space in the heap memory. Once you no longer need that variable, you should deallocate the memory being used for that variable by typing:
delete pointer;
This allows the memory to be used for other things.
These heap variables (new int) take up space in the heap memory. Once you no longer need that variable, you should deallocate the memory being used for that variable by typing:
delete pointer;
This allows the memory to be used for other things.
Nullify Heap Variables
Because a double deleted heap variable may cause your computer to crash, you should also nullify that variable immediately after deleting it:
delete pointer;
pointer = 0;
Because a double deleted heap variable may cause your computer to crash, you should also nullify that variable immediately after deleting it:
delete pointer;
pointer = 0;
Heap Arrays
In order to work with arrays in heaps, you will need to first allocate memory for the array, shown here in one step rather than two:
int * ptr = new int[80];
When you are assigning individual elements of the array, you do so the same way you would a normal array:
ptr[1] = 20
In order to work with arrays in heaps, you will need to first allocate memory for the array, shown here in one step rather than two:
int * ptr = new int[80];
When you are assigning individual elements of the array, you do so the same way you would a normal array:
ptr[1] = 20
Deleting Heap Arrays
When you are finished using the heap array, you will delete it thus:
delete[ ] ptr;
When you are finished using the heap array, you will delete it thus:
delete[ ] ptr;
Heap Const Variables
A normal variable may take a const variable's value, but a const variable may not take non-const variable. The same applies for const pointers.
A const pointer will turn a non-const to a const.
No comments:
Post a Comment