简体   繁体   中英

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 ;

If you are asking whether delete[] roadnodes; will implicitly delete roadnodes[0]; delete roadnodes[1]; ... delete roadnodes[0]; delete roadnodes[1]; ... 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM