Homework, Assigning pointers within a struct in C

130 views Asked by At

I'm making a Binary Tree as a part of my homework.

This is the given struct:

typedef struct TreeNode {
    int data;
    struct TreeNode* left;
    struct TreeNode* right;
}

My build_tree function is recursive, and this is the prototype:

void build_tree(TreeNode** root, const int elements[], const int count);

The homework is meant to partly test dynamically allocated memory. So my problem keeps happening when I try to assign a value to one of the pointers inside the struct. I have seen questions similar to this, but it never seems to be this question exactly, but still involves structs and pointers. If I misunderstood, I apologize for duplicating questions.

The build_tree method has to be done recursively This is my code for when an element should be inserted to the right of the root:

if(elements[0] > (*root)->data){
    TreeNode newnode = {elements[0], NULL, NULL}; //make a node to add
    *((*root)->right) = newnode; //dereference the root.right pointer, and set to newnode (GIVES COMPILE ERROR HERE)
    struct TreeNode **rightptrptr = malloc(sizeof((*root)->right)); //allocate a pointer to a pointer
    *rightptrptr = (*root)->right; //dereference pointer to a pointer, assign to root.right pointer
    build_tree(rightptrptr, new_elems, count - 1);
}

If it's important, the root node has been initialized to {an integer, NULL, NULL}.

My understanding of pointers isn't all that sophisticated, so please forgive me if this code is horrendous.

1

There are 1 answers

1
Jack On BEST ANSWER

There are many issues here, I'll try to point them out:

  • TreeNode newnode = {elements[0], NULL, NULL};, this allocates the struct on the stack, which means that the address of newnode (&newnode) won't be valid anymore when exiting the scope of the function.
  • if you need to build the tree by dynamically allocating the nodes TreeNode newnode = {elements[0], NULL, NULL} is not what you are looking for. This is not a dynamically allocated object, it's on the stack and the only thing you can do it with it to copy the content to an allocated node. You need always to allocate TreeNode* node = calloc(sizeof(TreeNode)) in your situation
  • ((*root)->right) = newnode, here you dereference the pointer to assign newnode to it. It could work but only if right points to allocated memory, which is not the case since your root initializes it to NULL. You should instead allocate directly the pointer, eg root->right = calloc(sizeof(TreeNode))
  • struct TreeNode **rightptrptr = malloc(sizeof((*root)->right)), here you allocate a pointer to a pointer to a TreeNode because the recursive function expects this but your approach is wrong. You should pass the pointer to an existing subtree, not allocating one with no purpose, you can do it by doing, for example &root->right.