【发布时间】:2018-01-05 14:36:00
【问题描述】:
我正在尝试使用 C 中的结构创建树
#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 指针,它编译并成功运行。我知道树不需要 * next 指针,但我不明白为什么它不会因为另一个相同的指针而编译。 感谢您的帮助。
【问题讨论】:
-
struct node * kosong = (struct node*)malloc(sizeof(struct node*));-->struct node * kosong = malloc(sizeof(struct node));(同样next未初始化。) -
1.不正确的格式是 [struct node * = (char *) malloc(size)] 吗?
-
2.为什么下一个未初始化是原因?
-
bluepixy 提到的格式是正确的。 Don't cast memory allocation functions in C.
-
我刚刚编译它,我得到了段错误