I'm using Visual C++ 2010. I have the following function to convert a System::String^ object to char pointer (char*).
void string2charPtr(System::String^ original, char *&out) {
int length = original->Length;
out = new char[length+1];
for (int i = 0; i < length; i++)
out[i] = (char) original[i];
out[length] = '\0';
}
Example of use:
int main(void) {
char* cPtr;
System::String^ str = gcnew System::String("Hello");
string2charPtr(str, cPtr);
delete cPtr;
return 0;
}
Is the "delete cPtr" instruction necessary? Or if I don't call it, there will be a memory leak?
Because you allocated an array, the correct statement is this:
And yes, without it, you have a memory leak. In this particular case, it doesn't really matter much, since the program ends immediately afterward, and the memory is then recovered by the OS.