L10 DMA of an Array of Objects
double pointers
Continuing from L09: Double pointers can be dereferenced twice to gain access to the original data type, whereas single pointers can be dereferenced once to gain access to the original data type.
delete a memory address that has already been freed.This produces an error.
arr[0] <=> *(arr)
arr[1] <=> *(arr + 1)
array of pointers
When you create an array of pointers, the pointer to that array is a double pointer.
So, this looks like:
int** arr2p = new int*[4];
// pointers in the array are uninitialized
Then, to assign actual pointers to int values in the array:
for (int i = 0; i < 4; i++) {
arr2p[i] = new int;
}
And to assign actual values:
for (int i = 0; i < 4; i++) {
*arr2p[i] = i+1;
// dereference the array at ith index to make the pointer at the ith index point
// to an int of i+1
}
When freeing the array, we have to delete the array last, otherwise we will have a memory leak. So, we delete each individual int first:
for (int i = 0; i < 4; i++) {
delete arr2p[i]; // deletes the pointers that point to an int
*arr2p[i] = NULL; // setting the value at that addrses to NULL as good practice
}
delete []arr2p;
// frees the entire array of int, after the individual ints have already been freed
array of objects
Building on to L09 and using the same Student class, we can create an array of objects:
Student* arr = new Student[3]; // creating an array of 3 Student objects
// calls constructor 3 times
delete []arr; // frees up entire array of objects, destructor called 3 times
An array of Student*:
Student** arr2p = new Student*[3];
// array of pointers that point to Student objects
// i.e. arr2p is a double pointer
i didn't really catch what this part of the lecture was supposed to be:
for (int i = 0; i < 3; i++) {
arr2p[i] = new Student;
}