Here I have an array of dynamically-allocated c-strings.
What is the proper way to free such an array?
It is necessary to individually free each element of
A, as code below?
Thank you.
#include <string.h>
int main()
{
const char** A = new const char*[3];
A[0] = (const char*)memcpy(new char[5], "str0", 5);
A[1] = (const char*)memcpy(new char[5], "str1", 5);
A[2] = (const char*)memcpy(new char[5], "str2", 5);
// Is this the proper way to free everything?
for (int i = 0; i < 3; ++i)
delete[] A[i];
delete[] A;
}
std::vector<std::string>and leave the memory management to the standard library?vector<string>.#include <string>-- Yet you failed to usestd::string. This is the header that definesstd::string,std::wstring, etc. I don't know what else you expected when you included this header.c-strings are faster than library strings-- Nothing stopped them from writing a simple C++ class that handles strings. If they were competent, it shouldn't have taken more than an hour.std::stringand doing it yourself. When you get the added benefits of all the built in functions, memory safety and ease of use it is worth usingstd::string. About the only time not to is if you know you have/need a fixed sized buffer.