Function with pointer to pointer

Asked

Viewed 317 times

-1

I have the following function

NOTE: In this function is only the first case, so it doesn’t get too big. Since the error occurs right at the first insertion.

int insertAVL_TreeR(struct AVL_TreeNode **node, void *elem, int *h) {
        if (!node) {//se o nó não existir, é criado um novo no
            AVL_TreeNode *novo = (AVL_TreeNode*) malloc(sizeof (AVL_TreeNode));
            novo->elem = elem;
            novo->fb = 0;
            novo->left = NULL;
            novo->right = NULL;
            node = novo;
            *h = 1; //haverá mudança na altura
        } else {

Which is called in right function

int insertAVL_Tree(struct AVL_Tree *tree, void *elem) {
    if (!tree)return 0;
    int *h = (int*) malloc(sizeof (int));
    *h = 1;
    AVL_TreeNode **p = &tree->root;
    int x = insertAVL_TreeR(*p, elem, h); //a chamada se dá nesta linha
    return x;
}

I want to know what the right way to move this pointer to pointer is. Because inside the function I get a Warning and everything goes well, but when it goes back to main, avl->root (previously initialized as NULL) goes on pointing to NULL.

My structs are these

typedef struct AVL_TreeNode
{
  void *elem;
  struct AVL_TreeNode *left;
  struct AVL_TreeNode *right;
  int fb;
}AVL_TreeNode;

and

typedef struct AVL_Tree 
{
  struct AVL_TreeNode *root;
}AVL_Tree;

1 answer

2


The call that of the method insertAVL_TreeR is wrong, the Node parameter is a double pointer, which would be its variable AVL_TreeNode **p. and when calling the method, you send as parameter the memory address that is within p. The correct thing would be to pass the p without the *, because then it would pass the memory address that has the reference of your tree->root. Thus remaining:

int x = insertAVL_TreeR(p, elem, h);

Now in your method of insertAVL_TreeR the error is where you assign the value to node. node is an independent variable that stores a memory address, assigns some value to it, will not change at all the node of your tree, so how to do? It is known that the value of node is the address that stores your node, so you need to change the value from within the Node this way.

(*node) = novo;

/*
node = <Endereço de tree->root>
(*node) = tree->root
*/

This way you can change the value of your node.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.