I have this code :
typedef struct node
{
int data;
struct node *left;
struct node *right;
} node;
void Build (node *root , int i)
{
if (i < 7)
{
root = (node *)malloc (sizeof(node));
root->data = i;
Build(root->left,2*i+1);
Build(root->right,2*i+2);
}
else
root = NULL;
}
void Print (node *root)
{
if (root)
{
printf ("%d ",root->data);
Print(root->left);
Print(root->right);
}
}
void main()
{
node *tree;
Build(tree,0);
Print(tree);
}
two things that I dont understand ,
1. why can’t I pass Build(tree,0) ? it says it’s uninitialized , but why shuold I care if it’s uninitialized ? I’m allocating all the memory needed straight away so it’s gonna be pointing on the new allocated node.
how can I fix this code? thank you!!!
Your
node *to tree is uninitialized.That matters because the code line
allocates memory to a local copy of root. Once you leave function scope of Build, the copy of root goes out of scope. Memory leak.
Remember, everything is passed by value in C.
If you really want Build to allocate the memory, the signature would have to be
and your code in that method would have to refer to
*rootinstead ofroot.