BST空指针赋值错误

时间:2012-11-12 06:45:50

标签: c runtime-error binary-search-tree null-pointer

我尝试实现BST程序但由于运行时错误导致执行失败。请告诉我如何纠正它。我创建树的代码是:

struct node *createBinTree()
{ int val,size;
   struct node *bintree, *newnode;
   bintree= NULL;
   printf("Enter the values of nodes terminated by a negetive no.\n");
   val=0;
   while(val>=0)
   {
     printf("\nEnter value");
     scanf("%d",&val);
     if(val>=0)
     { newnode = (struct node*)sizeof(struct node);
    newnode->val=val;
    newnode->lchild= NULL;
    newnode->rchild= NULL;
    bintree=attach(bintree,newnode);
     }
   }
   return bintree;
   }
   struct node *attach(struct node *tree,struct node* tnode)
   {if(tree==NULL)
     tree=tnode;
     else{
     if(tnode->val<tree->val)
      tree->lchild= attach(tree->lchild,tnode);
      else
      tree->rchild= attach(tree->rchild,tnode);

   }
   return tree;
  }

2 个答案:

答案 0 :(得分:0)

newnode = (struct node*)sizeof(struct node);

这不是您创建节点的方式。要么您没有使用malloc,要么忘记将其包含在您的代码中。相反,您直接为其分配地址,这是绝对不推荐的。将其更改为使用malloc,您应该没问题。

答案 1 :(得分:0)

newnode = (struct node*)sizeof(struct node);

您在while循环

中的上一行中缺少malloc()

使用它:

newnode = (struct node*)malloc(sizeof(struct node));