2015-05-22 44 views
0

我创建了两个结构尖锐的数据不断消失

typedef struct node 
{ 
    struct node* left; 
    struct node* right; 
    int data; 
} node; 

typedef struct head 
{ 
    int count; 
    struct node* root; 
} head; 

,这里是我试图使用将数据插入到一棵树的功能之外吧。

int insert(struct node* root, int value) 
{ 
    node* newnode =(node*)malloc(sizeof(node)); 
    newnode->data=value; 
    newnode->left=NULL; 
    newnode->right=NULL; 
    if(root==NULL) 
    { 
     root=newnode; 
     return 1; 
    } 
    if(value<root->data) 
    { 
     if(root->left==NULL) 
     { 
      root->left=newnode; 
      return 1; 
     } 
     else 
     { 
      return insert(root->left,value); 
     } 
    } 
    else if(value==root->data) 
    { 
     printf("data already exist\n"); 
     free(newnode); 
     return 0; 
    } 
    else 
    { 
     if(root->right==NULL) 
     { 
      root->right=newnode; 
      return 1; 
     } 
     else 
     { 
      return insert(root->right,value); 
     } 
    } 
} 

,当我操作

head* BSThead=(head*)malloc(sizeof(head)); 
insert(BSThead->root,10); 

我可以看到,插入功能成功地进入第一和如果操作线根= newnode,和我可以看到,它已给出的地址。

但是当这个函数结束时,我回到主函数来通过 来访问它printf(“%d”,BSThead-> root);

这行只是打印0,我认为这意味着BST-> root目前为空。

据我所知,由malloc函数创建的数据具有与正常值不同的功能范围。所以我认为虽然newnode是在插入函数中创建的,但是在插入函数结束时不会像正常变量一样被销毁,因此我可以在程序运行时随时使用它。

+1

你可能需要传递指向该函数根节点指针的指针。或者你可以从函数返回新的根节点指针。对于具有相同基本诊断的SO,存在很多问题。但是,您还会将未经检查的未初始化数据从'malloc()'传递给函数,这也可能导致很多麻烦。 –

回答

2

这些行:

if(root==NULL) 
{ 
    root=newnode; 
    return 1; 
} 

修改功能root,但不调用函数改变同一变量的值。

调用函数中的root的值继续为NULL,并且您将由调用分配的每个节点泄漏到malloc

解决此问题的一种方法是将指针传递给root

int insert(struct node** root, int value) 
{ 
    ... 
    if(*root==NULL) 
    { 
     *root=newnode; 
     return 1; 
    } 

    ... 
} 

,并呼吁使用功能:

insert(&(BSThead->root),10); 
1

的一个问题是,你正在使用:

head* BSThead = (head*)malloc(sizeof(head)); 
insert(BSThead->root, 10); 

这传递一个未经检查的指针未初始化的数据的功能。只有在你不幸的时候,它才会成为你传递的空指针。该函数无法修改BSThead->root中的值,因为您正在传递其值,而不是指向它的指针。您还没有通过整个head结构,因此insert()代码无法更新计数。

你需要在使用它之前初始化你的头部结构。当你使用它,你需要或者指针传递给头结构到功能,或者您需要的root成员的地址传递给函数,这样函数可以更新:

head* BSThead = (head*)malloc(sizeof(head)); 
if (BSThead != 0) 
{ 
    BSThead->count = 0; 
    BSThead->root = 0; 
    /* Either */ 
    insert(BSThead, 10);   // And insert can update the count 
    /* Or */ 
    insert(&BSThead->root, 10); // But insert can't update the count! 
    …use the list… 
    …free the list… 
}