The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
x
0 votes
49 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 by Veteran (95.9k points) | 49 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

 

in your code line 3

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

1 Answer

0 votes

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);
answered by (15 points)
0

why need to assign in root again?

root = insert(root,10);

it is already returning value

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.
	}


Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

39,658 questions
46,733 answers
140,425 comments
58,146 users