[英]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.