所以我正在尝试编写一个方法来删除一个节点以及连接到它的所有节点,但我对于该怎么做感到困惑。我知道free方法释放了所使用的内存,当我创建节点时,我使用了malloc。我不确定为什么free不会删除节点,我该怎么做。
struct node {
char *data;
struct node *left;
struct node *right;
}*child = NULL;
void delete(node* root){
char array[13];
node *toDelete;
//takes in name of node to be deleted
//scan method to find the node to delete and deletes all of the children of the node first before deleting
printf ("Please specify a name to delete\n");
scanf("%s", array);
toDelete = scan(root, array); //return which node to delete
removeChild(&toDelete); //helper method here to go through and delete each children
if(toDelete == NULL) {
printf("ERROR -- Node does not exist");
}
}
void removeChild(node **trash){
if((*trash)->left == NULL && (*trash)->right == NULL) { //no parents
free(trash);
*trash = NULL;
}
else if((*trash)->left == NULL && (*trash)->right != NULL) { //have mother
removeChild((*trash)->right);
}
else if((*trash)->left != NULL && (*trash)->right == NULL) { //have father
removeChild((*trash)->left);
} else{ //have both
removeChild((*trash)->left);
removeChild((*trash)->right);
}
}
答案 0 :(得分:4)
我没有仔细查看您的代码,但我看到这不符合您的想法:
void removeChild(node * trash){
if(trash->left == NULL && trash->right == NULL) { //no parents
free(trash);
trash = NULL;
}
...
打算清除指针的最后一个语句只对参数执行此操作。调用者的指针(传递给removeChild()
)没有指针为NULL。那是因为传递给函数的参数被复制了。它们不是通过引用传递的。
据推测,其他代码可能依赖于被清除的指针,因此这不符合它。