這樣的價值,我想實現線索結構,到目前爲止一切正常,除了以下:C++返回值從函數不一樣的功能
當使用count_words功能,我打印出結果就在返回它之前,並且結果是正確的,但是當我在main中打印它時,它會變成一些未知的奇怪整數值。
typedef struct trie {
int words;
int prefixes;
struct trie *characters[26];
} node;
int find_character_location(int ascii) {
return ascii-97;
}
node * initialize() {
node * new_node = (node*)malloc(sizeof(node));
new_node->words = 0;
new_node->prefixes = 0;
//all english alphabet characters
for(int i=0; i<26; i++) {
new_node->characters[i] = NULL;
}
return new_node;
}
//when adding string use only english lowercase letters
//a=97 b=98 ... z=122
void add_string(node * root, string str) {
int str_size = str.size();
if(str_size == 0) {
root->words++;
return;
}
else {
int position = find_character_location(str[0]);
root->prefixes++; //character doesnt exists
if(root->characters[position] == NULL) {
root->characters[position] = initialize();
}
add_string(root->characters[position],
str_size==1?"": str.substr(1));
}
}
int count_prefixes(node *root, string prefix) {
int str_size = prefix.size();
if(prefix == "") {
cout<<"number of prefixes: "<<(root->prefixes)<<endl;
return (*root).prefixes;
}
int position = find_character_location(prefix[0]);
//character exists
if(root->characters[position] != NULL) {
count_prefixes(
root->characters[position],str_size==1?"":prefix.substr(1));
}
else {
cout<<"no prefixes, returning 0"<<endl;
return 0;
}
}
int count_words(node *root, string str) {
int str_size = str.size();
if(str == "") {
cout<<"Number of words: "<<root->words<<endl;
int ret = root->words;
return (int)ret;
}
int position = find_character_location(str[0]);
//that character exists
if(root->characters[position] != NULL) {
count_words(root->characters[position],
str_size==1 ? "" : str.substr(1));
}
else {
cout<<"no words, returning 0"<<endl;
return 0;
}
}
int main() {
node * root;
root = initialize();
add_string(root, "tomislav");
add_string(root, "tomislav");
add_string(root, "tomislav");
add_string(root, "todoric");
add_string(root, "tomahawk");
add_string(root, "tosad");
add_string(root, "tomo");
cout<<"Counting words"<<count_words(root, "tomislav");
return 0;
}
因此,例如,對於count_words(根,「托米斯拉夫」)在功能count_words它印3,但主要是印刷9872106
能否請你告訴我,我要去哪裏錯了?
首先正確縮進此代碼。 –
不確定是否與您的問題相關,但如果'str'不是空的,並且列表中有單詞,則實際上不會返回任何內容。 if(root-> characters [position]!= NULL)的'then'子句不包含'return'語句。 –