二叉树代码无法正常工作

q2v*_*ven 1 c pointers

我做了一个树形结构,从文件中读取单词并将它们注册到树中.但是enter()不能正常工作.我用gdb进行了调试并设置了一个断点线42.然后我进入了print *node print *root.

(gdb) print node
$9 = (struct node *) 0x603250
(gdb) print *node
$10 = {left = 0x0, right = 0x0, word = 0x0}
(gdb) print root
$11 = (struct node *) 0x0
(gdb) print *root
Cannot access memory at address 0x0
Run Code Online (Sandbox Code Playgroud)

为什么没有root积分?为什么不node->word指出给定的词?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

struct node {
  struct node *left;
  struct node *right;
  char *word;
};

static struct node *root = NULL;

void memory_error(void) {
  fprintf(stderr, "Error: Out of memory\n");
  exit(8);
}

char *save_string(char *string) {
  char *new_string;

  new_string = malloc((unsigned) (strlen(string) + 1));

  if (new_string == NULL)
    memory_error();

  strcpy(new_string, string);

  return (new_string);
}

void enter(struct node *node, char *word) {
  int result;

  if (node == NULL) {
    node = malloc(sizeof(struct node));
    if (node == NULL)
      memory_error();

    node->left = NULL;
    node->right = NULL;
    node->word = save_string(word);
    return;
  }

  result = strcmp(node->word, word);

  if (result == 0)
    return;

  if (result < 0)
    enter(node->right, word);
  else
    enter(node->left, word);
}

void scan(char *name) {
  char word[100];
  int index;
  int ch;
  FILE *in_file;

  in_file = fopen(name, "r");
  if (in_file == NULL) {
    fprintf(stderr, "Error: Unable to open %s\n", name);
    exit(8);
  }

  while (1) {
    while (1) {
      ch = fgetc(in_file);

      if (isalpha(ch) || (ch == EOF))
    break;
    }

    if (ch == EOF)
      break;

    word[0] = ch;
    for (index = 1; index < sizeof(word); index++) {
      ch = fgetc(in_file);
      if (!isalpha(ch))
    break;
      word[index] = ch;
    }

    word[index] = '\0';

    enter(root, word);
  }

  fclose(in_file);
}

void print_tree(struct node *top) {
  if (top == NULL)
    return;

  print_tree(top->left);
  printf("%s\n", top->word);
  print_tree(top->right);
}

int main(int argc, char *argv[]) {
  if (argc != 2) {
    fprintf(stderr, "Error: Wrong number of parameters\n");
    fprintf(stderr, "       on the command line\n");
    fprintf(stderr, "Usage is:\n");
    fprintf(stderr, "         words 'file'\n");
    exit(8);
  }

  scan(argv[1]);
  print_tree(root);
  return (0);
}
Run Code Online (Sandbox Code Playgroud)

我给这个程序提供了以下文本作为参数"a.txt".

apple
orange
lemon
banana
pine
stroberry
ruby
perl
python
c
Run Code Online (Sandbox Code Playgroud)

nne*_*neo 5

在任何时候你都没有分配root.因此它将永远留下来NULL.

请注意,在enter,您分配节点但不实际将结果节点保存在任何位置.您可能希望返回新节点,root = enter(root, word)而是执行此操作.