Aditya Nadig Aditya Nadig - 5 months ago 38
C Question

Reading a binary tree from the console in c

I am trying to read a binary tree into my program using the following function that i wrote.

void readTree(struct Dnode *root)
struct Dnode *temp;
struct Dnode *input;
char initData;

scanf(" %c",&initData);

else {
printf("going to left of %c\n",initData);
printf("going to right of %c\n",initData);

Everything is working fine except the fact that , in main the tree doesnt exist. Here is my main program:

int main()
int n=0;
struct Dnode *root=NULL;
printf("Enter the tree as it asks. Enter z whenever there is no children :\n");
printf("In main");


The program suddenly crashes after inputting the tree.Please help me.


You must understand that the values passed to a function as an argument and the parameter of the evoked function are the same, but totally different two local variables.

When your function readTree() is evoked, a local variable root is declared and the value is automatically initiated as the same value you passed into a function when evoked. The variable, root in main(), and the root in readTree() are different two variables but have the same value.

In the function readTree(), you're creating a new node and binding the returned value to the variable root in readTree(). As I wrote, the two roots are not identical. Therefore, your changes, bindings, have no effects out of the scope - readTree() and the root in main() remains unchanged.

To handle this problem, you must pass the pointer to pointer to struct Dnode.

Like this, in main function,

struct Dnode *root;

and readTree() must also be changed

readTree(struct Dnode **root)