(So I don't need to spend much time explaining what it does.
I have explained new before, if you need a refresher, see: click here)
new TYPE // Allocate space to store ONE variable of // the type TYPE new TYPE [ N ] // Allocate space to store N variables of // the type TYPE |
int *p; // p can store an address int i; p = new int[10]; // We are using array notation with a pointer variable ! p[0] = 12; p[1] = 23; p[2] = 34; p[3] = 45; p[4] = 56; p[5] = 67; p[6] = 78; p[7] = 89; p[8] = 90; p[9] = 111; for ( i = 0; i < 10; i++ ) { cout << p[i] << " "; } |
|
Example:
ListElem p; p = new ListElem; Result: |
The first ListElem can no longer be accessed (because the location is "forgotten")
Such memory variable is known as garbage
delete PointerVariable; |
Example:
ListElem p; p = new ListElem; // Allocate space for one ListElem variable ... delete p; // **** Deallocate space allocated !!! |
This means that the size of an array in Java can change during the program execution
This means that the size of an array in C++ cannot change during the program execution
int i, N; int *p, *q; /* ------------------------------------ Make an array ------------------------------------ */ N = 10; p = new int[N]; // array of 10 elements for ( i = 0; i < N; i++ ) p[i] = i; /* ------------------------------------ Double the side of the array ------------------------------------ */ q = new int[2*N]; // array of 20 elements for ( i = 0; i < N; i++ ) q[i] = p[i]; // Copy old array to new array delete(p); // **** Remember to free unused space !!! p = q; // Switch p over to the new array N = 2*N; // Remember new array size |
|