Medvednic
Medvednic

Reputation: 692

Proper way of deleting a char** array

I have a dynamically allocated char** array as a private member in one of my classes.

The first allocation occurs according to number of words

client_interests = new char* [n];

Later each index of the array is allocated according to length of the word + 1

char[i] = new char [strlen(word)+1];

Would this be the proper way of deallocating the memory of this member (the classes dtor is calling this function)?

void Client::deallocate()
{
    int i;
    for (i = 0; i < n; i ++) //loops through each word
    {
        delete [] client_interests[i]; //each word is an array of characters, hence delete [] is used
    }
    delete [] client_interests; //deallocating the pointer
    client_interests = NULL;
}

Thaks!

Upvotes: 1

Views: 156

Answers (3)

Taimour
Taimour

Reputation: 459

Yes this is the correct way of deallocating the 2d array.

delete []

is used to deallocate an array, and you are doing it correctly as you first deallocate the inner arrays and than the outer array.

Upvotes: 1

Jordan Samuels
Jordan Samuels

Reputation: 997

Your code is correct. Since you allocate using new [], de-allocating with delete [] as you do is required. Also, obviously de-allocating in reverse order - inner arrays first, then outer array - is also required.

Upvotes: 2

anderas
anderas

Reputation: 5844

Yes, if you absolutely cannot use std::vector<std::string>, then your way of deallocating things is correct.

Upvotes: 2

Related Questions