MrSn0w
MrSn0w

Reputation: 11

Deleting an array of Pointers

I am trying to create an AVL tree and i am using a dynamic array of pointers to track which nodes are affected by the insertion.My Question is if the deletion of the dynamic array will delete the content of the pointers as well.The code is not finished but i think it will give you an idea of what i mean.If it does not work then how should i do it?Thanks in advance.

treenode *newnode,**roadnodes,*parent ;
int x=(int)log(numberofnodes)+2,l=0 ;
bool *rightorleft,flag=true ;
newnode=new treenode ;
roadnodes=new treenode*[x] ;
rightorleft=new bool[x] ;
newnode->id=i ;
newnode->hl=0;
newnode->hr=0;
newnode->hm=0;
newnode->left=NULL;
newnode->right=NULL ;
if(head==NULL)
{
    delete[] roadnodes ;
    delete[] rightorleft ;
    numberofnodes++ ;
    head=newnode ;
    return true ;
}
parent=head ;
while(flag)
{
    roadnodes[l]=parent ;
    if(parent->id>i)
    {
        if(parent->left)
            parent=parent->left ;
        else
        {
            flag=false ;
            parent->left=newnode ;
        }
        rightorleft[l]=true ;
        l++ ;
    }
    else
    {
        if(parent->right)
            parent=parent->right ;
        else
        {
            flag=false ;
            parent->right=newnode ;
        }
        rightorleft[l]=false ;
        l++ ;
    }

}
return true ;

Upvotes: 1

Views: 74

Answers (2)

Slava
Slava

Reputation: 44238

Question is if the deletion of the dynamic array will delete the content of the pointers as well.

When you call delete on dynamic array then destructor of each element is called. As you may guess raw pointers do not have destructors or it is a noop so no, that memory would not be released. So you either use smart pointers which destructor would release memory or you need to call delete for each pointer manually.

Upvotes: 1

Fred Larson
Fred Larson

Reputation: 62053

If you are asking whether delete[] roadnodes; will implicitly delete roadnodes[0]; delete roadnodes[1]; ..., the answer is no. It absolutely will not. You are responsible for deleting them. Using standard containers and smart pointers, as suggested in a couple of comments, is a much better way to go.

Upvotes: 1

Related Questions