描述仅打印输入的最后一个

时间:2010-03-22 23:53:33

标签: c pointers binary-search-tree

我是C的新手,我正在尝试在C中实现一个二叉树,它将存储一个数字和一个字符串,然后将它们打印出来,例如。

1 : Bread
2 : WashingUpLiquid
etc.

我到目前为止的代码是:

#include <stdio.h>
#include <stdlib.h>
#define LENGTH 300

struct node {
 int data;
 char * definition;
 struct node *left;
 struct node *right;
};

struct node *node_insert(struct node *p, int value, char * word);

void print_preorder(struct node *p);

int main(void) {
  int i = 0;
  int d = 0;
  char def[LENGTH];
  struct node *root = NULL; 

  for(i = 0; i < 2; i++)
  {
    printf("Please enter a number: \n");
    scanf("%d", &d);
    printf("Please enter a definition for this word:\n");
    scanf("%s", def);
    root = node_insert(root, d, def);
    printf("%s\n", def);
  }

  printf("preorder : ");
  print_preorder(root);
  printf("\n");

  return 0;
}

struct node *node_insert(struct node *p, int value, char * word) {
  struct node *tmp_one = NULL;
  struct node *tmp_two = NULL;

  if(p == NULL) {
    p = (struct node *)malloc(sizeof(struct node));
    p->data = value;
    p->definition = word;
    p->left = p->right = NULL;
  }
  else {
    tmp_one = p;
    while(tmp_one != NULL) {
      tmp_two = tmp_one;
      if(tmp_one->data > value)
        tmp_one = tmp_one->left;
      else
        tmp_one = tmp_one->right;
    }

    if(tmp_two->data > value) {
      tmp_two->left = (struct node *)malloc(sizeof(struct node));
      tmp_two = tmp_two->left;
      tmp_two->data = value;
      tmp_two->definition = word;
      tmp_two->left = tmp_two->right = NULL;
    }
    else {
      tmp_two->right = (struct node *)malloc(sizeof(struct node)); 
      tmp_two = tmp_two->right;
      tmp_two->data = value;
      tmp_two->definition = word;
      tmp_two->left = tmp_two->right = NULL;
    }
  }

  return(p);
}

void print_preorder(struct node *p) {
  if(p != NULL) {
    printf("%d : %s\n", p->data, p->definition);
    print_preorder(p->left);
    print_preorder(p->right);
  }
}

目前它似乎适用于int,但描述部分仅打印输入的最后一个。我假设它与char数组上的指针有关,但我没有运气让它工作。任何想法或建议?

2 个答案:

答案 0 :(得分:2)

你总是在def中做一个scanf然后将它传递给你的插入例程,它只是将指针保存到def。因此,由于所有条目都指向def缓冲区,因此它们都指向存储在该缓冲区中的最后一个字符串。

您需要复制字符串并将指向该副本的指针放入二叉树节点。

答案 1 :(得分:1)

问题是你正在为字符串使用相同的缓冲区。请注意,您的struct持有一个指向char的指针,并且每次都传递与该指针相同的char数组。

当您在缓冲区上调用scanf时,您正在更改它指向的数据,而不是指针本身。

要解决此问题,在将其分配给结构之前,您可以使用strdup。所以代码行将成为

tmp_*->definition = strdup(word);

请记住,strdup返回的char数组一旦完成就必须被释放,否则你会有泄漏。