c - C语言的家谱

标签 c pointers

我正在编写一个家谱程序,但我无法从家谱中删除一个节点。我有一个 delete 方法,它获取要删除的节点的名称,找到它,然后将其删除。我释放了 trash 节点,我试图删除的节点,并将其设置为 NULL,但在我测试它时它仍然存在。我是否应该为节点分配新的左右路径而不是尝试将其设置为 NULL

struct node {
    char *data;
    struct node *left;
    struct node *right;
}*child;


void delete(node* root){
    char array[13];
    node *toDelete;
    printf ("Please specify a name to delete\n");
    scanf("%s", array);
    toDelete = scan(root, array); 
    if(toDelete == NULL) {
            printf("ERROR -- Node does not exist");
    } else {
    removeChild(&toDelete); 
    }
}

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

最佳答案

enter image description here

对不起。

无论如何,

// free a node and all its children.
// Return # of nodes freed.
int free_node_recursive(node * n){
    int total_freed = 1;

    // free the left child (if any)
    if(n->left != NULL){
        free_node_data(n->left);
        total_freed += free_node_recursive(n->left);
        n->left = NULL;
    }

    // free the right child (if any)
    if(n->right != NULL){
        free_node_data(n->right);
        total_freed += free_node_recursive(n->right);
        n->right = NULL;
    }

    // actually free the thing.
    free(n);

    return total_freed;
}

例如。

void delete(node* root){
    char array[13];
    node *toDelete;
    printf ("Please specify a name to delete\n");
    scanf("%s", array);
    toDelete = scan(root, array); 
    if(toDelete == NULL) {
        printf("ERROR -- Node does not exist");
    } else {
        free_node_recursive(&toDelete); 
    }
}

您的问题是,在全局树 (root) 中,对刚刚删除的节点的引用将仍然存在。沿着树向下的解析器会发现父级中的引用仍然完好无损,并尝试下降到它,发现数据已经空闲并且不可访问;段错误。

关于c - C语言的家谱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49655746/

相关文章:

c - 结构体函数的传递和返回

c - 如何编译 GCC 生成的 asm?

c++ - 如何在指针中保存 vector 元素的详细信息?

c - 重新分配:无效的下一个大小,由 glibc 检测到

c - Linux内核中如何判断一个inode是目录还是mot

C 套接字引发错误代码 22,EINVAL - 无效参数

objective-c - Objective-C 中有两个星号 ** 是什么意思?

c - 调用 realloc() 之前释放内存

更改指针指向的字符串

c - void * 函数指针