//binary tree
#include<stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node* lc;
struct node* rc;
}*ptr,*root;
void preorder(struct node* root){
if(root!=NULL){
printf("%d ",root->data);
preorder(root->lc);
preorder(root->rc);
}
}
struct node* create(){
int x;
ptr = (struct node*)malloc(sizeof( struct node ));
printf("type data value(enter -1 if not needed):\n");
scanf("%d",&x);
if(x!=-1){
ptr->data = x;
printf("Left child of %d:\n",x);
ptr->lc = create();
printf("Right child of %d:\n",x);
ptr->rc = create();
return ptr;
}
else{
return NULL;
}
}
void main(){
root = NULL;
root = create();
preorder(root);
}
This code above runs into an endless loop when executed. But when i declared the structure pointer variables locally instead of declaring it globally. It worked. like this...
struct node* create(){
int x;
struct node* ptr = (struct node*)malloc(sizeof( struct node ));
.......
void main(){
struct node* root = NULL;
Can someone explain to me why does the above code run into endless loop and how did declaring the variables locally fixed it?
i was trying to implement a binary tree data structure using recursive function create()... and the create function worked fine(i think) when i executed the code but the preorder() ran into an endless loop.
create()is a recursive functions. And when you callptr->lc = create();andptris a global variable, its value is overwritten by the recursive call and the assignment toptr->lcis really made to that node.Because of these traps you should really avoid using global variables in recursive functions (best: always avoid using global variables)