【发布时间】:2017-04-26 08:02:57
【问题描述】:
以下是我的 BST 插入函数代码。有人能解释一下为什么会出现分段错误吗?
#include <stdio.h>
#include <stdlib.h>
struct node{
int value;
struct node* right;
struct node* left;
};
struct node* insert(struct node* n,int age){
if (n==NULL){
n = malloc(sizeof(struct node));
n->value = age;
n->left = n->right = NULL;
}
else if(age < n->value){
n->left = insert(n->left, age);
}
else {
n->right = insert(n->right, age);
}
return n;
}
void main(){
int age;
struct node* n=NULL;
scanf("%d",&age);
while (age!=-1){
n=insert(n,age);
scanf("%d",&age);
}
}
我提到了this,它建议使用**(引用指针)。
f( &px );
//...
void f( int **px )
{
*px = malloc( sizeof( int ) );
printf( "*px = %p\n", *px );
}
但是为什么我们不能通过将返回类型从void 更改为node* 来避免使用**?
【问题讨论】:
-
insert总是崩溃。你的编译器不会对此发出警告吗? -
main应该返回int,而不是void。 -
您缺少
#include <stdlib.h>和#include <stdio.h>。 -
if (n=NULL){-->if (n==NULL){需要return n;end ofinsert -
@AlekhyaVellanki 因为
n=NULL将NULL分配给n,然后下面的n->value取消引用一个空指针。你用的是什么编译器?
标签: c pointers binary-search-tree