【问题标题】:Binary tree crashes when compiling [closed]编译时二叉树崩溃[关闭]
【发布时间】:2013-12-25 14:51:20
【问题描述】:

编译时似乎有错误,但不确定是什么。我已经经历了几次,不知道为什么。

另外,我还应该做些什么来改进这段代码?

#include <stdlib.h>
#include <stdio.h>

//create structure to hold node
typedef struct node
{
int data;
struct node *left;   //lower no. / points to left node
struct node *right;  //higher no. / points to right node
} node;

void insert(node **rt, int val)     //insertion function
{
node *tmp;

if(*rt == NULL){
    tmp = (node *) malloc(sizeof(node));        //allocates memory for node
    if (tmp == NULL)
    {
        printf(stderr, "Unable to allocate node\n");
        exit(1);
    }
    tmp->data = val;
    *rt = tmp;
}
else{
    if(val > (*rt)->data)
        insert(&(*rt)->right, val);
    else
        insert(&(*rt)->left, val);
}
}

void print_node(node *head)         //starts with head/first node until NULL
{
if(head == NULL)
    return;

if(head->left != NULL)
    print_node(head->left);
    printf("data = %d\n", head->data);

if(head->right != NULL)
    print_node(head->right);
}

int main(int argc, char *argv[])
{
int value[6] = {20,10,5,17,30,21};     //values put into array
int i;                                  //i count
node *head = NULL;
    for(i = 0; i < 6; i++)              //loop array
    {
        insert(&head, value[i]);
    }

print_node(head);               //recursive search

return 0;
}

【问题讨论】:

  • 编译时还是运行时?编译器崩溃会很奇怪。如果在运行时,您应该调试以缩小问题范围。

标签: c data-structures binary-tree nodes


【解决方案1】:

代码似乎错过了初始化新分配的nodeleftright 成员。

在此行之后修复此插入

    tmp->data = val;

缺少像这样的初始化:

    tmp->left = NULL;
    tmp->right = NULL;

代码也没有打印出正确节点的值。

【讨论】:

    【解决方案2】:

    在这行printf(stderr, "Unable to allocate node\n"); 我想你的意思是fprintf(stderr, "Unable to allocate node\n");

    【讨论】:

    • 令人担忧的是编译的代码出现了这个错误。它建议使用过时的编译器和缺少的头文件。话虽如此,代码已包含&lt;stdio.h&gt;,因此编译器确实没有理由不抱怨printf() 的滥用,这可能意味着代码已被“清理”以在SO 上呈现。咳!
    • 你是对的,他肯定应该改变编译器。在我修复了这个“错字”之后它工作得很好。
    猜你喜欢
    • 2015-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 2019-12-23
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    相关资源
    最近更新 更多