【问题标题】:My tree program crashes after inserting into one root node我的树程序在插入一个根节点后崩溃
【发布时间】:2013-10-02 04:54:40
【问题描述】:

我不太擅长制作树,而且我完全搞砸了递归。但是,我尝试编写一个程序来将数据插入和显示到树中。

问题是插入根节点后崩溃,不知道为什么。树不算大。只需 10 int

#include <stdio.h>
#include <stdlib.h>
#define SIZE 10;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
struct node{
    int data;
    struct node * left;
    struct node * right;
};


void insert(struct node * root,int num){
    printf("Insert called for num:%d\n",num);
    if(root == NULL){
        root = (struct node *)malloc(sizeof(struct node));
        root->data = num;
    }else if(num > root->data){ // Number greater than root ?
        insert(root->right,num); // Let the right sub-tree deal with it
    }else if(num < root->data){// Number less than root ?
        insert(root->left,num);// Let the left sub-tree deal with it.
    }else{
        // nothing, just return.
    }
}


void display(struct node * root){ // Inorder traversal
    if(root->left!=NULL){ // We still have children  in left sub-tree ?
        display(root->left); // Display them.
    }

    printf("%d",root->data); // Display the root data

    if(root->right!=NULL){ // We still have children in right sub-tree ?
        display(root->right); // Display them.
    }

}

int main(int argc, char *argv[]) {
    int a[10] = {2,1,3,5,4,6,7,9,8,10};
    int i;
    struct node * tree;

    for(i = 0; i < 10;i++){
        insert(tree,a[i]);
    }
    printf("Insert done");
    return 0;
}  

谁能告诉我哪里出错了?

我知道要求人们在 Stack 上查看您的代码是不受欢迎的,但有时 pair programming 有效:p

更新:
设置struct node * tree = NULL; 后,insert() 方法效果很好。 display() 导致程序崩溃。

【问题讨论】:

  • 我立即看到了问题。在分配之后,您永远不会将根节点 leftright 指针初始化为 NULL。 root by-val Grijesh 的传球已经介绍过了,所以我不会。
  • @LittleChild 实际上是我和 WhoCraig 的两个错误指针以及下面发布的另一个错误。全面检查您的代码维护
  • @WhozCraig 他们不是默认初始化为 NULL 吗?
  • @LittleChild No. malloc() 只是分配内存。内容是不确定的,直到在分配后对其进行初始化。本地变量也是如此(Crashworks 在下面的答案中指出了这一点)。
  • @LittleChild 是的,这使得所有分配的内存为零。也不要忘记初始化局部变量,就像 Crashworks 向您指出的那样。

标签: c recursion tree binary-search-tree


【解决方案1】:

在你的

int main(int argc, char *argv[]) {
    // ...
    struct node * tree;
    // what is the value of tree at this line?
    for(i = 0; i < 10;i++){
        insert(tree,a[i]);
    }
    // ...
} 

“树”在标记线处指向什么?

【讨论】:

  • tree 指向树的根节点。我简单地将其命名为tree。 :)
  • 不,我的意思是,在那一行:“树”变量中包含什么?如果你做了 printf("%x\n",tree);,你会看到什么?
  • 空。一开始,根节点应该是空的。
  • 是什么让“树”为空?
  • 您也没有初始化“树”。请记住,指针也是变量。 (就 CPU 而言,指针是包含地址的无符号整数。)如果不初始化变量,它会包含一些垃圾值。因此“树”指向一个随机地址。
猜你喜欢
  • 2017-10-28
  • 2021-11-08
  • 1970-01-01
  • 1970-01-01
  • 2021-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多