有人可以解释一下下面的二进制搜索插入代码有什么问题吗?当我尝试插入第二个元素时出现段错误。
node * insert(node * root, int value)
{
if(root == NULL){
node *newnode = (node *)malloc(sizeof(node));
newnode->data = value;
newnode->left = NULL;
newnode->right = NULL;
root = newnode;
}
else{
if(root->data > value)
insert(root->left, value);
if(root->data < value)
insert(root->right, value);
}
return root;
}
int main(){
node* root = NULL;
root = insert(root, 5);
root = insert(root, 10);
}
最佳答案
您必须包含 stdlib.h
。
否则,编译器不知道malloc
的原型(prototype),并假定它返回一个int
而不是一个指针。如果您的 ABI 以不同方式对待指针和整数,则会导致问题。
相应的警告被类型转换隐藏了。
关于c - 二进制搜索树插入抛出段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34351907/