What is the correct way to delete char**

不打扰是莪最后的温柔 提交于 2019-12-09 14:32:53

问题


I have a char**, basically an array of strings, that I need to delete. What is the correct way of doing this to ensure all pointers are cleared up?


回答1:


char** StringList ;
int nStrings ;
....
for (int i = 0 ; i < nStrings ; i++)
  delete[] StringList[i] ;
delete[] StringList ;

Of course, it's simpler if you start with

std::vector<std::string> Stringlist ;

Then it's just

StringList.clear() ;



回答2:


The rule of thumb is that you need one delete (or delete[]) for each new (or new[]) that you issued.

So if you did:

char **pp = new char*[N];
for (i = 0; i < N; i++)
{
    pp[i] = new char[L];
}

then you will need to clean up with:

for (i = 0; i < N; i++)
{
    delete [] pp[i];
}
delete [] pp;

However, it should be noted that as you are in C++, you should probably be using std::vector<std::string> rather than arrays of arrays of raw char, because it would manage its own clean-up.




回答3:


Do pattern matching as described below :

char *arr = new char[10];
char *p = new char;

delete [] arr;
delete p;

Did you see the pattern when to use what?

So now go to the original question:

char **dp = new char*[100]; //100 number of `char*`
for ( int i = 0  ; i < 100 ; i++ ) //loop for 100 times
    dp[i] = new char[30];  //allocate memory for each `char*`

 //deallocate
 for ( int i = 0  ; i < 100 ; i++ ) 
    delete [] dp[i]; //deallocate memory for each `char*`
 delete [] dp; //deallocate memory for `char**`



回答4:


for(int i = 0; i < array_length; ++i)
{
    delete[] array[i]; // delete each entry in the array (assuming you used new[] for each string)
}

delete[] array; // delete the actual array.



回答5:


I assume that you have array like this:

char **pp = new char* [10];  // for the base pointer
for(int i = 0; i < 10; i++)
  pp[i] = new char[100]; // for every char* string

You should follow the reverse order. First clean up the member strings and then main pointer.

for(int i = 0; i < 10; i++)
  delete[] pp[i];
delete[] pp;



回答6:


for (int i = rows; i > 0; --i) {
 delete[] anArray[i-1];
}
delete[] anArray;


来源:https://stackoverflow.com/questions/5989670/what-is-the-correct-way-to-delete-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!