1

私は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);
  }
}

現時点ではints で動作しているようですが、最後に入力した説明部分のみが出力されます。char配列のポインターと関係があると思いますが、うまく機能しませんでした。アイデアやアドバイスはありますか?

4

2 に答える 2

2

あなたは常にdefにscanfを実行し、それをdefへのポインタを保存する挿入ルーチンに渡します。したがって、すべてのエントリが def バッファを指しているので、それらはすべて、そのバッファに保存した最後の文字列を指しています。

文字列をコピーし、そのコピーへのポインタをバイナリ ツリー ノードに配置する必要があります。

于 2010-03-23T00:00:54.350 に答える
1

問題は、文字列に同じバッファーを使用していることです。構造体が char へのポインターを保持しており、毎回そのポインターと同じ char 配列を渡していることに注意してください。

バッファーを呼び出すとscanf、ポインター自体ではなく、バッファーが指すデータが変更されます。

これを修正するには、構造体に割り当てる前に、strdupを使用できます。したがって、コード行は次のようになります

tmp_*->definition = strdup(word);

strdup によって返される char 配列は、使い終わったら解放する必要があることに注意してください。そうしないと、リークが発生します。

于 2010-03-23T00:03:47.920 に答える