C中节点值自动改变

Node value changing automatically in C

我正在为二叉搜索树创建一个程序,这是我正在使用的一个函数。如输出所示,值 root->rightChild 由于未知原因正在更改,程序结束时没有显示任何错误。

typedef struct node * BST;
struct node
{
  struct node *leftChild;
  int data;
  struct node *rightChild;
};
BST temp=NULL, ptr=NULL, root=NULL, prev=NULL;
BST newNode()
{
  BST X;
  X=(BST)malloc(sizeof(BST));
  X->leftChild=X->rightChild=NULL;
  return X;
}

void createBST(int elem)
{
  temp=newNode();
  temp->data=elem;
  if(!root)
  {
    root=temp;
    printf("\nroot-?rightChild= %p",root->rightChild);
    printf("\nroot-?leftChild= %p",root->leftChild);
  }
  else
  {
    printf("\nroot-?rightChild= %p",root->rightChild);
    printf("\nroot-?leftChild= %p",root->leftChild);
    prev=NULL;
    ptr=root;
    while(ptr!=NULL)
    {
      prev=ptr;
      ptr=(ptr->data<temp->data)?ptr->rightChild:ptr->leftChild;
    }
    if(prev->data<temp->data)
      prev->rightChild=temp;
    else
      prev->leftChild=temp;
  }
}
int main()
{
  int choice;
  while(1)
  {
    printf("\nPick a Binary Search Tree operation\n1) Create a Binary Search Tree\n2) Traverse the Binary Search Tree\n3) Seach for a KEY element in the Binary Search Tree\n4) Exit\n>| ");
    scanf("%d",&choice);
    switch(choice)
    {
      case 1:
      {
        int num,elem;
        printf("\nEnter the number of elements to be inserted into the Binary Search Tree: ");
        scanf("%d",&num);
        printf("\nEnter the elements to be inserted into the Binary Search Tree: ");
        for(int i=1;i<=num;i++)
        {
          scanf("%d",&elem);
          createBST(elem);
        }
      }
      break;
      case 2:
        traverBST();
      break;
      case 3:
        searchBST();
      break;
      case 4:
        exitProgram();
      break;
      default:
        printf("\nInvalid Choice\n");
      }
    }
    return 0;
}

这是代码的输出:

此语句有错字

X=(BST)malloc(sizeof(BST));
                     ^^^

即调用 malloc 为指向节点的指针而不是节点本身分配内存。

一定有

X=(BST)malloc(sizeof( *X));

X=(BST)malloc(sizeof( struct node ));

由于打字错误,程序有未定义的行为。