Why does this search function return a pointer to a pointer?

感情迁移 提交于 2019-12-13 20:05:03

问题


#ifndef _BST_H_

/* Returns negative (left<right), zero (left==right), or positive (left>right). */
typedef int comparator(void* left, void* right);

struct bst_node {
    void* data;
    struct bst_node* left;
    struct bst_node* right;
};

struct bst_node* new_node(void* data);
void free_node(struct bst_node* node);
struct bst_node** search(struct bst_node** root, comparator compare, void* data);
void insert(struct bst_node** root, comparator compare, void* data);
void delete(struct bst_node** node);

#endif

This is a header file. I don't understand about search function, why is the return type node**?

Edited: added search func here:

struct bst_node** search(struct bst_node** root, comparator compare, void* data) {
    struct bst_node** node = root;
    while (*node != NULL) {
        int compare_result = compare(data, (*node)->data);
        if (compare_result < 0)
            node = &(*node)->left;
        else if (compare_result > 0)
            node = &(*node)->right;
        else
            break;
    }
    return node;
}

回答1:


I would guess that the function returns a pointer to a pointer so that your search function can be used to implement insert. If search just returns a pointer to a node and the node isn't found, then you have to walk the tree again to figure out what pointer you need to rewire to do an insertion. If it instead returns a pointer to the node pointer that ended up being null, then insert can be implemented by just reassigning this pointer to point to the new node that needs to be inserted.

Just a guess.



来源:https://stackoverflow.com/questions/5373905/why-does-this-search-function-return-a-pointer-to-a-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!