二叉树产生Segmentation Fault
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;
}
您永远不会为价值分配 space。将定义更改为整数。
typedef struct Node
{
struct Node* right;
struct Node* left;
int value;
} Node;
然后
n->value = val;
和
printf("value : %d\n", tree->value);
Node
类型的 value
成员从未设置为 NULL
以外的任何值。由于它的值是一个空指针,所以使用语句*(n->value) = val;
是不合适的;它试图取消引用空指针。
如果您希望 value
指向一个 int
,您必须为一个 int
分配内存并将 value
设置为该内存的地址。如果您希望 value
成为 int
,则必须更改其声明以及使用它的代码。
我是 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;
}
您永远不会为价值分配 space。将定义更改为整数。
typedef struct Node
{
struct Node* right;
struct Node* left;
int value;
} Node;
然后
n->value = val;
和
printf("value : %d\n", tree->value);
Node
类型的 value
成员从未设置为 NULL
以外的任何值。由于它的值是一个空指针,所以使用语句*(n->value) = val;
是不合适的;它试图取消引用空指针。
如果您希望 value
指向一个 int
,您必须为一个 int
分配内存并将 value
设置为该内存的地址。如果您希望 value
成为 int
,则必须更改其声明以及使用它的代码。