以下程序旨在使用strcmp函数按字母顺序在二进制搜索树中存储单词。程序中详述的问题是,函数的最后一部分函数的递归调用中没有传递指针。递归函数在参数不为NULL时传递NULL指针
typedef struct NodT{
char word[30];
struct NodT *left, *right;
} NOD;
void reset_field(NOD *nod){
int i;
for(i=0; i<30; i++){
nod->word[i]='\0';
}
}
void enter_recursively(NOD *nod, char *word){
if(nod==NULL){
nod= (NOD *) malloc(sizeof(NOD));
nod->left=NULL;
nod->right=NULL;
reset_field(nod);
strcpy(nod->word, word);
return;
}
if(nod->word[0]=='\0'){
strcpy(nod->word, word);
return;
}
if(strcmp(nod->word, word)==0) return;
if(strcmp(nod->word, word)<0){
enter_recursively(nod->right, word);//the problem seems to be here
printf("right\n");
}
else{
enter_recursively(nod->left, word);//...and here
printf("left\n");
}
//the NULL pointer is being sent over, which is peculiar
}
的事情是,当我通过从结构的指针(左,右)的递归函数中的if-else条件,它需要对另一侧上的NULL值,其中当不可这样做的原因是,在分配第一个单词之后,第二个单词在右侧或左侧,取决于strcmp,在malloc用于为单词创建新存储空间时进行分配。
更新:使用双指针的新的脚本:
typedef struct NodT{
int key;
char word[30];
struct NodT *left, *right;
} NOD;
void enter_recursively(NOD **nod, char *word){
printf("N: %p\n", nod);
printf("NL: %p\n", (**nod).left);
printf("NR: %p\n", (**nod).right);
if(nod==NULL){
nod=malloc(sizeof(NOD));
(**nod).left=NULL;
(**nod).right=NULL;
strcpy((**nod).word, word);
return;
}
if((**nod).word[0]=='\0'){
strcpy((**nod).word, word);
return;
}
if(strcmp((**nod).word, word)==0) return;
if(strcmp((**nod).word, word)<0){
enter_recursively((**nod).right, word);
}
else{
enter_recursively((**nod).left, word);
}
我得到分段错误,我不知道为什么。
把检查'点头== NULL'(或只是'nod' :)之前你曾经试图访问其内容。你可能只是倾销你的堆栈访问。 –
请在您的编译器中启用警告,您使用'return;'在无效函数中使用,这是没有意义的。同样,你的拳头'NULL'检查将永远不会匹配,如果'nod'在函数入口处为null,则会在此之前进行段错误检测。 – Mat
哦对不起,我已经重新编辑了。取得了回报;现在有意义 –