5.3 Dynamic Variable
1. Creation
-
new <type-name>
Keyword new allocates room in the heap to a dynamic variable and return its address as a pointer, and if you want to use it later, you must use a pointer to store it.
-
new <type-name> [integral-expression]...[integral-expression]
The expression above create a dynamic array and return the address of its first element.
-
#include <cstdlib> void* malloc(unsigned int size);
Built-in function
malloc
allocated a room of input size in the heap and return its start address as a general pointer, which needs a explicit type reversion to your target type. Here are some examples.int *p1 = (int *)malloc(sizeof(int)); //create a int dynamic variable int *p2 = (int *)malloc(sizeof(int) * n); //create a int dynamic array with n rooms
2. Revoke
Usually, we use keyword
delete
to revoke dynamic variables created by keywordnew
and functionfree
to revoke dynamic variables created by functionmalloc
.
delete <pointer>;
//revoke the dynamic variable pointed by the pointer
delete []<pointer>;
//revoke the dynamic array pointed by the pointer
#include <cstdlib>
free(<pointer>);
//revoke the dynamic variable or array pointed by the pointer
Notice that if you want to revoke a dynamic array, the pointer must point to its first element.
When we have revoked a dynamic variable, the pointer is still there pointing to its room which is empty now. So the pointer has become a dangling pointer.
Moreover, if there’s a dynamic variable has not been revoked and the pointer previously pointing at it has pointed somewhere else or ended its lifetime, the dynamic variable here will become an orphan - no longer able to be accessed while continue to occupy the room, which is a waste of the memory. This phenomenon is called memory leak.
3. Application - Dynamic Array
Use dynamic array is a method to solve the problem that the regular array must be defined with fixed length.
//if we know the number of numbers
int n, *p;
cin >> n;
p = new int[n];
for (int i = 0; i < n; i++) cin >> p[i];
sort(p, n);
delete []p;
//if end with a flag
int max_len = 20, count = 0, n;
const int INCREMENT = 10;
int *p = new int[max_len];
cin >> n;
while (n != -1) {
if (count >= max_len) {
max_len += INCREMENT;
int *q = new int[max_len];
for (int i = 0; i < count; i++) q[i] = p[i];
delete []p;
p = q;
}
p[count] = n;
count++;
cin >> n;
}
sort(p, count);
delete []p;