当我在我的 main 中调用 find_word 函数时,我不断收到段错误。 当添加一个单词时,我想返回 1,当它找到那个单词时,我希望它返回 1。 所以我也不确定我的插入方法是否正确。
#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;
}
最佳答案
这样修复
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
struct node {
char *word;
struct node *left;
struct node *right;
};
static struct node *root = NULL;
static int insert(struct node **newnode, char *word){
struct node *temp = NULL;
int cmp;
if(!*newnode){
temp = (struct node *)malloc(sizeof(struct node));
temp->left =NULL;
temp->right = NULL;
temp->word = strdup(word);
*newnode = temp;
return 0;
}
if((cmp=strcmp(word, (*newnode)->word)) < 0)
return insert(&(*newnode)->left, word);
if(cmp > 0)
return insert(&(*newnode)->right, word);
return 1;
}
int add_word(char *word){
return insert(&root, word);
}
static int find(char *word, struct node *newnode){
int cmp;
if(newnode==NULL)
return 0;
if((cmp=strcmp(word, newnode->word)) == 0)
return 1;
if(cmp < 0)
return find(word, newnode->left);
return find(word, newnode->right);
}
int find_word(char *word){
return find(word, root);
}
int main(int argc,char *argv[]){
int k;
char *w;
k = add_word(w="x");
printf("add_word(%s): %d\n", w, k);
k = find_word(w);
printf("find_word(%s): %d\n", w, k);
return 0;
}
关于c - BST 中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21617817/