I'm learning C++ from Stroustrop's A Tour of C++ 2E and I'm playing around with his examples.
I have a struct Vector
, with a member elements
that is a pointer to an array of doubles. I'm trying to delete[]
the array which I allocated with new[]
, but even if there are no compile- or run-time errors, the array does not seem to be getting deleted. What's going on here?
#include <iostream>
struct Vector {
int size;
double* elements;
};
void print_array(double* first, int size) {
double* cursor = first;
for (int i = 0; i < size; ++i) {
std::cout << *cursor << " ";
++cursor;
}
std::cout << "\n";
}
int main() {
Vector v;
v.size = 5;
v.elements = new double[5];
for (int i = 0; i < v.size; ++i) {
v.elements[i] = 9-i;
}
print_array(v.elements, v.size);
delete[] v.elements;
std::cout << "v.elements==nullptr ? " << (v.elements==nullptr) << "\n";
print_array(v.elements, v.size);
return 0;
}
The output I'm getting is:
9 8 7 6 5
v.elements==nullptr ? 0
9 8 7 6 5
I do not yet know what will happen if I print out a deleted array, but I'm baffled as to why the third line in the output is happening at all. Thanks in advance.