这是我使用gcc -Wall -ansi -g的程序代码

该程序制作二叉树并按顺序打印。但是我有问题。

我不能将root设置为NULL,而必须分配我认为应该将其标记为NULL的内存。

还有另一个问题。如果没有NULL但分配了内存,它如何工作? malloc是否在NULL上分配(*root) -> right_childleft_child的内存。我完全不明白。如果我不这样分配内存,则会出现分段错误。任何帮助和批评家都将受到欢迎。

#include <stdlib.h>
#include <stdio.h>
/*struct for node it has pointers and value*/
struct node {
    struct node *left_child ;
    struct node *right_child;
    int val;
};

/*Prints error message out of memory*/

void outOfMemoryError(void){
    fprintf (stderr,"out of memory error :(\n");
    fflush(stderr);
    exit (123);
}

/*print tree inorder*/
void printTreeInOrder (struct node **rootNode){
    if ( (*rootNode) == NULL)
    {
#ifdef DEBUG
        printf("## my node is null");
#endif

        return;
    }
    if ( (*rootNode)->left_child !=NULL){
        printTreeInOrder( (*rootNode) ->left_child);
    }

    printf ("%d ",(*rootNode) ->val);
    if ((*rootNode)->right_child !=NULL){
        printTreeInOrder((*rootNode)->right_child);
    }
}

/*add node uses recursion*/
void addNode (struct node **root, int value ){
    if ( (*root) == NULL) {
#ifdef DEBUG
        printf("## my root is null\n");
        fflush (stdout);
#endif
        (*root) = malloc (sizeof (struct node));

        if (root == NULL)
            outOfMemoryError();
        (*root) ->val = value;
        /* I don't know why I have to malloc this memory instead using NULL*/
        (*root) ->left_child = malloc (sizeof (struct node));
        (*root) ->right_child = malloc (sizeof (struct node));
    }
    else if ((*root) ->val > value){
        addNode ((*root)->right_child,value);
    }
    else
        addNode ((*root)->left_child,value);

}

int main(void)
{
    /*input vars*/
    char string [80];
    int temp = 0;

    /*root of the whole tree*/
    struct node *root = malloc (sizeof (struct node));

    printf ("i will add to binnary tree as long as int is bigger than 0\n");
    while (1) {
        fgets (string,sizeof(string),stdin);
        sscanf(string,"%d",&temp);
        if (temp <= 0)
            break;
        addNode(root,temp);
    }
    printf("Printing tree Inorder\n");
    printTreeInOrder(root);
    return 0;
}

最佳答案

如果我正确阅读了addNode函数应该执行的操作,则第一个malloc就会发生内存泄漏。

=>您将指针传递给struct node的指针(即:struct node* * [注意空格])。因此,addNode应该更新struct node*以反映新的根。这就是为什么您需要传递地址的原因(例如:&root)。

我希望addNode使用该指针来创建(例如:malloc)新的struct node并存储到调用方以获取新值。例如:

struct node* root = NULL;

...

addNode(&root, temp);


在addNode中:

    (*root) ->left_child = NULL;
    (*root) ->right_child = NULL;


因为根据设计,left_child将是一个“根”(addNode的第一个参数),它将创建该节点。

然后:

   else if ((*root) ->val > value){
        addNode (&((*root)->right_child),value);
   } else {
        addNode (&((*root)->left_child ),value);
   }


因为如果不传递指向root->left/right_child的指针,它将不会更新struct node*的内容。

09-27 06:02