开发者

What is the correct way to delete char**

开发者 https://www.devze.com 2023-03-05 09:41 出处:网络
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 pointer开发者_开发技巧s are cleared up?The rule of thumb is that you need one

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 pointer开发者_开发技巧s are cleared up?


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.


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() ;


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**`


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.


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;


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号