【发布时间】:2013-11-22 05:28:06
【问题描述】:
所以,我正在为大学的一门课做作业,目标是构建一个字符串 BST,用于读取文本、划分文本并将每个单词插入树中。
但是我在尝试(手动)插入一个单词时遇到了分段错误,你们能告诉我我哪里做错了并建议修复吗?
/* Structure for the node */
typedef struct node {
char *key;
int multi;
struct node *left, *right;
} node;
node *root;
void Insert(char *x, node *p){
p = root;
/* if the pointer points to null, create a new node and insert the key */
if (*p == NULL){
(*p) = (node)malloc(sizeof(node))
(*p)->key = strcpy((*p)->key, x);
(*p)->left = NULL;
(*p)->right = NULL;
return;
}
else if (strcasecmp(x, p->key) < 0)
{
Insert(x, &p->left);
return;
}
else if (strcasecmp(x, p->key) > 0)
{
Insert(x, &p->right);
return;
}
/* if the words are equal, add 1 to the multi (how many times the word appears */
else
(*p)->multi = multi + 1;
}
【问题讨论】:
-
那甚至不应该编译!当您将
p声明为指针时,您不能这样做,例如(*p)->key...然后稍后您就可以正确使用它,例如p->key. -
还有,为什么要传入
p作为参数,然后直接重新赋值为指向root? -
坦率地说,这段代码是一堆未定义的行为。将 (unnecessary) 从
malloc()硬转换为甚至不是指针类型的类型是唯一可以避免编译失败的方法。它迅速从那里走下坡路。 -
很抱歉,我的代码是另一种语言(不是英文),我不得不进行一些更正以使其易于理解,并且在此过程中出现了一些错误
标签: c string segmentation-fault binary-search-tree