【发布时间】:2011-12-23 00:25:30
【问题描述】:
以下程序旨在使用 strcmp 函数在二叉搜索树中按字母顺序存储单词。这个问题,在程序下详细说明,是在函数的最后部分的函数的递归调用中没有传递指针。
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,分配第一个词在root中,第二个词在右边或左边后不为NULL,使用malloc为词创建新存储空间时的alocation。
更新:使用双指针的新脚本:
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);
}
我遇到分段错误,我不知道为什么。
【问题讨论】:
-
在您尝试访问其内容之前,请勾选
nod == NULL(或只是nod:)。您可能只是在使用这些访问权限转储您的堆栈。 -
请在你的编译器上启用警告,你在一个没有意义的非空函数中使用
return;。此外,您的拳头NULL检查将永远不会匹配,如果nod在函数入口处为空,您将在此之前出现段错误。 -
抱歉,我重新编辑了。退货;现在有意义
-
这与您的问题没有直接关系,但
for (i = 0; i < 30; i++) { nod->word[0] = '\0'; }没有意义。 -
@pmg,这只是我用来清除所有字符串以写入文件的函数。我已经添加了它,以防你们中的一些人发现它影响了其他功能。哦......我的糟糕我直到现在才注意到那个功能。那里应该是 word[i]。
标签: c pointers recursion reference binary-tree