【发布时间】:2017-03-01 12:59:29
【问题描述】:
这是我正在使用的三个结构,例如当我的程序 将 'the' 作为第一个单词,它使 *rt->str = the. 但是,当读取下一个单词时,密钥等于 *rt->str,我不明白为什么。我是一名 c 程序员初学者,这真的让我停了下来。
struct node {
char *str;
int occ;
struct node *sibling;
struct node *child;
};
struct node* root;
struct node* getNew(char word[100]) {
struct node *newNode;
newNode = (struct node *)malloc(sizeof(struct node));
newNode->str = word;
newNode->sibling = NULL;
newNode->child = NULL;
newNode->occ = 0;
return newNode;
}
struct node* insert( char key[100], struct node **rt ){
if(*rt == NULL) {
*rt = getNew(key);
printf("This is the key in the root: %s\n", (*rt)->str);
return *rt;
}else{
printf("root word: %s\n", (*rt)->str);
exit(0);
}
struct node *leaf = *rt;
int n = 0;
int i;
char w2[100];
strcpy(w2, key);
printf("root word: %s\n", (*rt)->str);
for(i = 0; i < strlen((leaf)->str); i++) {
printf("%c %c \n", (leaf)->str[i], key[i]);
if((key[0] == (leaf)->str[i])) {
n++;
key = key + 1;
printf("key is: %s \n", key);
}
}
if(key[0] == 0) {
printf("key is empty \n");
}
printf("This is the word after for loop: %s \n", key);
exit(0);
}
【问题讨论】:
-
if (...) return ..; else exit();使函数的其余部分无法访问。 -
学习使用调试器。每次你的代码没有达到你想要的效果时,你都不会走得太远。
-
同样在
getNew,newNode->str = word;你可能想在这里使用strdup。