繁体   English   中英

二叉树产生分段错误

[英]Binary tree produce Segmentation Fault

我是 C 的新手,想从编写一个简单的二叉树开始。 push 和 traverse 函数都存在问题,但我花了两天时间弄清楚程序。 当我编译并执行程序时,它显示分段错误。 代码如下,任何帮助将不胜感激。 谢谢

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>

typedef struct Node
{
  struct Node* right;
  struct Node* left;
  int* value;
} Node;

Node* init()
{
  Node* t = (Node*) malloc(sizeof(Node));
  t->left = NULL;
  t->right = NULL;
  t->value = NULL;
  return t;
}

int traverse(Node* tree)
{
  printf("value : %d\n", *(tree->value));
  if (tree->left != NULL) {
    traverse(tree->left);
  } else if (tree->right != NULL){
    traverse(tree->right);
  }
}

void push(Node* n, int val)
{
  if (n->value == NULL)
  {
    *(n->value) = val;
  } else if (n->left == NULL && val < *(n->value)) {
    n->left = init();
    push(n->left, val);
  } else if (n->right == NULL && val > *(n->value)) {
    n->right = init();
    push(n->right, val);
  }
} 

int main(int argc, char const *argv[])
{
  srand(time(NULL));
  Node* tree = init();

  for (unsigned int i = 0; i < 20; ++i)
  {
    int val = rand() % 10;
    push(tree, val);
    printf("%d\n", val);
  }

  traverse(tree);
  printf("%s\n", "End Of Program!");
  return 0;
}

你永远不会为价值分配空间。 将定义更改为 integer。

typedef struct Node
{
  struct Node* right;
  struct Node* left;
  int value;
} Node;

接着

n->value = val;

printf("value : %d\n", tree->value);

Node类型的value成员永远不会设置为NULL以外的任何值。 由于它的值是一个 null 指针,使用语句*(n->value) = val; 不合适; 它试图取消引用 null 指针。

如果您希望value指向int ,则必须为int分配 memory 并将value设置为该 memory 的地址。 如果您希望value成为int ,则必须更改其声明以及使用它的代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM