我正在尝试使用 C 中的 struct 创建一棵树
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node * next, * left, * right;
};
struct node * createtree(int data){
struct node * kosong = (struct node*)malloc(sizeof(struct node*));
kosong->data = data;
kosong->left = kosong->right = NULL;
return kosong;
}
void printtree(struct node * tree){
if(tree == NULL) return;
printtree(tree->left);
printf("%d ",tree->data);
printtree(tree->right);
}
int main(){
struct node * pohon = NULL;
pohon = createtree(1);
pohon->left = createtree(2);
pohon->right = createtree(3);
pohon->left->left = createtree(4);
pohon->left->right = createtree(5);
printtree(pohon);
}
每当我编译它都会出现分段错误。然后我尝试删除 * next 指针,它编译并成功运行。我知道树不需要 * 下一个指针,但我不明白为什么它不会因为另一个相同的指针而编译。感谢您的帮助。
为了帮助您理解错误:
函数 createtree(int data) 中的第一行:
struct node * kosong = (struct node*)malloc(sizeof(struct node*));
实际上应该是
struct node * kosong = (struct node*)malloc(sizeof(struct node));
因为您正在为结构节点分配内存,而不是为指向结构节点的指针分配内存。
这就是您的段错误的实际原因。我编译了代码,只修复了这个错误,它工作得非常好。当然,您应该尝试初始化所有指针和变量,因为不初始化可能会导致未定义的行为,这可以是任何事情,就像分段错误一样。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句