Reprint: Two fork tree build up the pointer problem

Source: Internet
Author: User

Tag:blog   ar   io    use    sp    data    div    problem    log   

#include <stdio.h> #include <stdlib.h> struct Bitnode {char data;     struct bitnode* lchild;  The structure of binary tree struct bitnode* rchild;  };  typedef struct BITNODE * BITREE; void Creatbitree (Bitree); Create two fork tree void Preordertraverse (Bitree);      Traverse the two-fork tree to print the value of each node void main () {Bitree t=null;//t is the root node Creatbitree (T);      Preordertraverse (T);      System ("pause"); return 0;      }//Set up a two-fork tree void Creatbitree (Bitree T) {Char ch with the pre-order recursive process;      Ch=getchar ();      if (ch = = ' * ')//If an asterisk is entered, the node of the two-fork tree is an empty node t=null; else{if (!          (t= (Bitree) malloc (sizeof (struct bitnode)))) {printf ("Memory allocation failed!                 "); return; If the input is not an asterisk.              Allocates a memory space for the new node} else {t->data=ch; Creatbitree (T->lchild);          The allocation succeeds then establishes Saozi right subtree Creatbitree (t->rchild); }}} void Preordertraverse (Bitree t) {if (t) {printf ("%c", t->dATA);; if (t->lchild) preordertraverse (t->lchild);      Traverse the tree, outputting the values of the individual nodes if (t->rchild) preordertraverse (t->rchild); }  }

  

First of all we know that there is a problem, where there is a problem, to create a two-fork tree when there is a problem, to see what the value of the pass, pass the pointer, and accept the parameter is a pointer, this is nothing to do with our ordinary function is a variable received or a common variable, think about, when the call function ends, Its space still exists, then you pass over the value of the parameter will be returned to your main function, obviously is not possible ah, so the modified code is as follows:

#include <stdio.h> #include <stdlib.h> struct Bitnode {char data;     struct bitnode* lchild;  The structure of binary tree struct bitnode* rchild;  };  typedef struct BITNODE * BITREE; void Creatbitree (Bitree); Create two fork tree void Preordertraverse (Bitree);      Traverse the two-fork tree to print the value of each node void main () {Bitree t=null;//t is the root node Creatbitree (T);      Preordertraverse (T);      System ("pause"); return 0;    }//Establish two-fork-tree void Creatbitree (Bitree * T) {char-ch with the pre-order recursive process;    Ch=getchar ();    if (ch = = ' * ')//If an asterisk is entered, the node of the two-fork tree is an empty node *t=null; else {if (!         (*t= (Bitree) malloc (sizeof (struct bitnode)))) {printf ("Memory allocation failed!                 "); return; If the input is not an asterisk.             Allocates a memory space for the new node} else {(*t)->data=ch; Creatbitree (& (*t)->lchild);         The allocation succeeds then establishes Saozi right subtree Creatbitree (& (*t)->rchild);          }}} void Preordertraverse (Bitree t) {if (t) {printf ("%c", t->data);; if (T-&GT;lchild) Preordertraverse (t->lchild);      Traverse the tree, outputting the values of the individual nodes if (t->rchild) preordertraverse (t->rchild); }  }

  

In the binary tree, the individual thinks that beginners can easily make a few mistakes:

1: Create a two-fork tree with two types of patterns:

A: Define a bitree in the main function note that this is a pointer type for a binary tree node, and then pass this parameter to a Creatbitree function, and in that function recursively create a two-tree; The code is as follows:

void Creatbitree (Bitree * T)//Note I use a level two pointer here; this is where many people are prone to make mistakes;         {                 char ch;                 Ch=getchar ();                if (ch = = ' * ')//If an asterisk is entered, the node of the two-fork tree is an empty node                    *t=null;               else{                       if (! (*t= (Bitree) malloc (sizeof (struct bitnode)))) {                               printf ("Memory allocation failed! ");                                 return; If the input is not an asterisk. Allocates a memory space for the new node                       }                       else                      {                                (*t)->data=ch;                                 Creatbitree (& (*t)->lchild); The allocation succeeds then establishes the Saozi right subtree                                creatbitree (& ((*t)->rchild);}}}       

  

B: You can create a two-fork tree directly in the Creatbitree function and return the root pointer of the binary tree;

such as: Bitree T=creatbitree (); Code is as follows:

Bitree Creatbitree ()          {                     char ch;                      Bitnode *pt=null;                     Ch=getchar ();                     if (' * ' ==ch)                              return NULL;                     else {                              pt= (Bitnode *) malloc (? Bitnode));                              pt->data=ch;                              Pt->lchild=creatbitree ();                              Pt->rchild=creatbitree ();                              return pt;           }

  

Oh.. From the top of the two achievements process, it is still the second easy to understand a little:

However, most people are puzzled by the question, that is, in the first (that is, a) in the process, why must use two-level pointers, and first level why not??

Instead of passing pointers in a function, changing the value of a pointer in a function is changing the data information in the argument???

The amount ... In fact, the above said is also right, but the problem is in this piece ... The problem is that in the process of building a two-fork tree, it is not changing the value of the formal parameter, but rather: changing the direction of the formal parameter, and after the function is released, the parameters are freed, so there is no way to release the space of the parameter, which causes the memory leak problem.

Let's take an example:

void Get_vale1 (char *pt) {       pt= (char *) malloc (strlen ("Sx_liang") +1);        strcpy (PT, "Sx_liang"); }void Get_vale2 (char **pt) {       *pt= (char *) malloc (strlen ("Sx_liang") +1);        strcpy (*pt, "Sx_liang"); }int Main () {         char *pt=null;            Get_vale1 (PT); See, in the process of calling here, pass the first level pointer;           if (null==pt)//amount .... In this case, the information inside the IF is executed ...          {                       cout<< "pt is NULL" <<endl;                       Exit (1);          }           else                cout<<pt<<endl;                Get_vale2 (&PT); Here, pass the two-level pointer, the result, the output of "Sx_liang";         if (null==pt)           {                       cout<< "PT is NULL

  

What's the reason: I'm starting to analyze:

void Get_vale1 (char *m)//Here, a pointer is passed, at which point the same amount of space that the M and the argument PT point to the memory points to null;

m= (char *) malloc (strlen ("Sx_liang") +1); At this point, the re-opening of a space for M, and the actual parameter pt does not change, but also point to null;

It is here, M and PT have no contact, completely turned into two points to different pointers;

strcpy (M, "Sx_liang");//Exit Function, because M is a local variable, allocated in the stack of space, then M automatically destroyed, and in the heap for m allocated space, leaked, not released; it's a problem!

void Get_vale2 (char **m)//Here, pass a level two pointer; At this point, M points to the argument, not the same as the argument null;*m at this point, the same as PT, pointing to null; pay attention to experience;

*m= (char *) malloc (strlen ("Sx_liang") +1);//Here, *m is the real parameter pt, to the *m application space, is to apply for the space for PT; pay attention to experience;

strcpy (*m, "Sx_liang");//After the function is introduced, M destroys, but the space it applies for is not released, but the space has PT pointing to it, not worry about releasing the problem;

The amount ... Here, you should be able to understand why the binary tree in the process of the creation of a method to use the level two pointer .... The first level of pointers, each created node, there is no connection with the head pointer root, of course, there is no way to print, and the level two ... Oh... It's OK ....

That's it. Oh...

Reprint: Two fork tree build up the pointer problem

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.