【问题标题】:BST null pointer assignment errorBST 空指针赋值错误
【发布时间】:2012-10-31 14:53:35
【问题描述】:

我尝试实现 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;
  }

【问题讨论】:

  • 您希望这能做什么? newnode = (struct node*)sizeof(struct node);
  • 如果您还没有使用过调试器,那么现在正是使用它的最佳时机。在调试器中运行程序将帮助您找到崩溃的位置,并让您查看调用堆栈以便您知道它是如何在该位置结束的,还可以让您检查变量以帮助您找出可能导致的原因崩溃。
  • 请告诉我们错误是什么!使用帖子末尾的“编辑”链接并添加此信息。

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


【解决方案1】:
newnode = (struct node*)sizeof(struct node);

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

【讨论】:

  • 哦,是的,我忘了包括它。非常感谢你:)
【解决方案2】:
newnode = (struct node*)sizeof(struct node);

您在 while 循环的上述行中缺少 malloc()

使用这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-16
    相关资源
    最近更新 更多