我正在編寫一個C++應用程序,以跨歌詞歌詞的大型數據庫進行單詞搜索。開始,我以每一個字,並把它變成一個字結構,看起來像這樣:在C++中將結構指針設置爲空時,存儲值消失
struct Word{
char* clean;
int size;
int position;
SongId id;
Word* same;
Word* diff;
};
我有一個「makeNode」功能,執行以下操作:
- 發生在每一個字
- 創建一個新的Word結構,並增加了字它
- 創建一個Word *稱爲節點指向新詞
- 存儲指針在哈希表。
在我的makeNode函數中,我將node-> clean設置爲我的「乾淨」字。我可以通過cout'ing node-> clean打印這個單詞。但是,當我將node->設置爲NULL時,我會丟失node-> clean。我不會失去節點 - >位置或節點 - >大小。如果我刪除了將node-> same分配給NULL的行,我不會丟失node-> clean。
char* clean = cleanse(word);
Word* node = new Word;
node->size = strlen(word);
node->clean = clean;
cout<<"MADE NODE FOR "<<node->clean<<endl;
node->position = position;
cout<<"4 node clean: "<<node->clean<<endl;
node->id = id;
cout<<"5 node clean: "<<node->clean<<endl;
node->same = NULL;
cout<<"6 node clean: "<<node->clean<<endl;
cout<<"node position: "<<node->position<<endl;
cout<<"node size: "<<node->size<<endl;
node->diff = NULL;
產生以下的輸出:
MADE NODE FOR again
4 node clean: again
5 node clean: again
6 node clean:
node position: 1739
node size: 6
0 node clean:
1 node clean:
3 node clean:
誰能幫我把過去的這個錯誤?如果您需要更多信息,請告訴我。提前致謝!
編輯:這裏是清理功能。
char* SongSearch::cleanse(char* dirty)
{
string clean;
int iter = 0;
while (!isalnum(dirty[iter]))
{
iter++;
}
while(dirty[iter]!='\0')
{
clean += dirty[iter];
iter++;
}
int backiter = clean.length() - 1;
while(!isalnum(clean[backiter]))
{
clean.erase(backiter, 1);
backiter--;
}
char c;
for (int i = 0; i<clean.length(); i++)
{
c = tolower(clean[i]);
clean[i] = c;
}
char* toReturn = (char*)(clean.c_str());
return toReturn;
}
什麼是'cleanse'?一個函數?發佈其代碼。它返回本地char數組嗎? – Nawaz 2011-05-01 18:03:07
如果你做某事的時候傷害了,不要這樣做。停止使用char *,Word *並使用std :: strings和Word的向量。並重新考慮你的struct的名字 - 爲什麼叫做Word? – 2011-05-01 18:08:38