> Say I do the following:
char **names = new char*[100];
for (int i = 0; i < 100; i++) {
names[i] = new char[5];
}
When I'm done with the array of character pointers, how should I
delete it? Like this:
for (int i = 0; i < 100; i++) {
delete names[i];
}
delete[] names;
or like this:
delete[] names;
Basically, does delete[] call each individual delete or not? If so,
what happens if I do the former method? Assuming it doesn't, then I guess
the second method would create a memory leak.
Others have already answered your question. But I think you should know
that your code will become a lot simpler and safer when you replace the
C style arrays with the C++ classes std::vector and st::string. The code
you posted for allocating and deallocating a collection of names could
be reduced to:
std::vector<std::string> names(100);
Not only is this code shorter, but both std::vector and std::string can
(easilly) dynamically grow to accommodate more names and/or longer names
(i.e. no arbitrary length limitation). When the names object runs out of
scope (e.g. because of function return or exception) all memory
allocated on its behalf will automatically be freed. If you have to
delete the memory manually like in the code you posted, it can be rather
tricky not to leak memory when an exception occures.
--
Peter van Merkerk
peter.van.merkerk(at)dse.nl