当我在main中调用find_word函数时,我总是收到分段错误错误。 当一个单词被添加我想返回1,当它发现这个词,我想它返回1.所以我也不确定我的插入方法是否正确。BST中的分段错误错误
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
struct node {
char *word;
struct node *left;
struct node *right;
};
static struct node *root;
int init(void)
{
struct node *new_node = malloc (sizeof(struct node));
if(new_node==NULL){
return 0;
}
else{
root = new_node;
new_node->left = NULL;
new_node->right = NULL;
return 1;
}
}
static int insert(struct node *newnode, char *word)
{
struct node *temp = NULL;
if(!(newnode))
{
temp = (struct node *)malloc(sizeof(struct node));
temp->left =NULL;
temp->right = NULL;
temp->word = word;
newnode = temp;
return 0;
}
if(word < (newnode)->word)
{
insert((newnode)->left, word);
}
else if(word > (newnode)->word)
{
insert((newnode)->right, word);
}
return 1;
}
int add_word(char *word)
{
return insert(root,word);
}
static int find(char *word, struct node *newnode){
if(newnode==NULL){
return 0;
}
else if(strcmp(word,newnode->word)>0){
find(word,newnode->left);
}
else if(strcmp(newnode->word,word)<0){
find(word,newnode->right);
}
else{
return 1;
}
return 0;
}
int find_word(char *word)
{
return find(word,root);
}
int main(int argc,char *argv[])
{
int k;
char l[5];
k = init();
printf("init: %d\n",k);
strcpy(l,"x");
k = add_word(l);
printf("add_word(%s): %d\n",l,k);
strcpy(l,"x");
k = find_word(l);
printf("find_word(%s): %d\n",l,k);
return 0;
}
'insert'应该使用'strcmp'比较'和'newnode-> word',不''<' and '> word'。 – Barmar
@Barmar我在'insert'中改了它,现在它的'strcmp(word,newnode-> word)> 0'和'strcmp(word,newnode-> word)<0',但是我仍然遇到了分割错误。 – Mark
你之前没有发布类似的问题吗?看起来它已被删除,因为我现在找不到它。正如我在那里建议的那样,在调试器下运行你的代码,这样你就可以在错误发生时看到哪些变量是无效的。 – Barmar