64 views

Why not this code not printing 10?

(It is just a binary tree with one node i.e. root. And value of root is 10)

#include <stdio.h>
#include<stdlib.h>
struct BinaryTree *root=NULL;
struct BinaryTree{
int data;
struct BinaryTree *left;
struct BinaryTree *right;
};

struct BinaryTree *node(int data)
{
struct BinaryTree *node;
node=(struct BinaryTree*)malloc(sizeof(struct BinaryTree));
node->data=data;
node->left=node->right=NULL;
return node;
}
struct BinaryTree *insert(int *root,int data1){
if(root==NULL){
root=node(data1);
return root;
}
}
int main() {
insert(root,10);
printf("%d",*root);
return 0;
}


asked in DS | 64 views
0
printf("%d",*root);

printf("%d",*root->data);

insert(root,10);

you are passing root as structure pointer but in insert (int *root,int data1) ===> function receiving as integer pointer and moreover return value of insert (int *root,int data1) function didn't catch by main function therefore your global root didn't update

struct BinaryTree *root=NULL;

i hope it will give compilation error, dueto upto line 3 BinaryTree didn't declared as Structure

0

still not giving right output

https://ideone.com/neWNU8

0
@srestha, you haven't change the datatype of root in insert function that's why it is giving error.

chk this- https://ideone.com/CCLgqU
0
The function insert is modifying local parameter root. That's why

Either you pass the root node by reference like:

insert(&root,10);
struct BinaryTree *insert(int **root,int data1)

Or you assign the returned pointer to node to the root node like:

root = insert(root,10);
0

root = insert(root,10);

rt?

0

Since you are passing the value of the address of root to the insert function, which is NULL. The changes (i.e: assigning a memory using the node function) reflected won't be existing outside the scope of insert function. You are returning the value of the address that is newly assigned but there is no assignment for that value to be stored in root again. So returning is useless in this case, when you don't assign it.

Alternatively,

void *insert(int **root,int data1){
if(*root==NULL){
*root=node(data1);
//You don't need returning here, since we are using addresses.
}

1
2