【发布时间】:2014-02-07 01:48:45
【问题描述】:
当我在 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;
}
【问题讨论】:
-
insert应该使用strcmp来比较word和newnode->word,而不是<和>。 -
@Barmar 我更改了它,所以它现在是
strcmp(word,newnode->word)>0和strcmp(word,newnode->word)<0在insert但我仍然收到分段错误。 -
你之前不是发过类似的问题吗?好像被删了,因为现在找不到了。正如我在那里建议的那样,在调试器下运行您的代码,以便在发生错误时查看哪些变量无效。
-
我做了,但我认为这会提供更多背景信息。我会尝试调试。
-
您可能只是更新了原始问题而不是发布新问题。
标签: c segmentation-fault