我正在制作一个预测文本界面,通过该界面我将字典存储到数据结构中(我使用了 trie),用户部分地搜索一个词,并显示完整的词,并显示每个词对应的数字。我已经完成了插入、搜索功能,并进行了递归遍历,打印出所有完整的单词(没有数字)。但是我想将它们存储到一个结构中,以便我可以在另一个函数中使用它们,然后用户将看到带有相应数字的单词。
这是 main.c 代码(为了测试它不会进入输入所有 25 000 个单词的 readfile!):
struct TrieNode* root = trieRootConstructor();
struct TrieNode* pntr = NULL;
trieInsert(root, "aback");
trieInsert(root, "abacus");
trieInsert(root, "abalone");
trieInsert(root, "abandon");
trieInsert(root, "abase");
trieInsert(root, "abash");
trieInsert(root, "abate");
trieInsert(root, "abater");
int x = 0;
char* result = "";
char* search = "aba";
result = trieSearch(root, &pntr, search, result, &x);
printf("\n\n");
traverseTwo(pntr, search);
pntr 设置为部分单词结束的节点,这是遍历将搜索单词其余部分的位置。
这是我的递归遍历及其调用者:
void traverseTwo(struct TrieNode* node, char* partialWord)
{
char arr[50];
int index = 0;
int maxWordSize = 100;
char wordArr[50][maxWordSize];
index = recursivePrint(node->children, arr, wordArr[50], 0, partialWord, index);
int i = 0;
for(i = 0; i < index; i++)
printf("%d: %s\n", i, wordArr[i]);
printf("%d: Continue Typing", index);
}
int recursivePrint(struct TrieNode* node, char* arr, char* wordArr, int level, char* partialWord, int index)
{
if(node != NULL)
{
arr[level] = node->symbol;
index = recursivePrint(node->children, arr, wordArr, level+1, partialWord, index);
if(node->symbol == '\0')
index = completeWordAndStore(partialWord, arr, wordArr, index);
index = recursivePrint(node->sibling, arr, wordArr, level, partialWord, index);
}
return index;
}
int completeWordAndStore(char* partialWord, char* restOfWord, char* wordArr, int index)
{
int length = strlen(partialWord) + strlen(restOfWord);
char completeWord[length];
strcpy(completeWord, partialWord);
strcat(completeWord, restOfWord);
strcpy(wordArr[index], completeWord);
index++;
return index;
}
我在 strcpy(wordArr[index], completeWord);
想法(在我的脑海中)是,一旦它进入节点符号为 '\0' 的 if 语句,它将在索引值处存储字符串。
partial word是已经搜索过的部分词ee.g“aba”,我会用arr对其进行strcat并将其存储到结构中。
结果应该产生:
0: 大吃一惊 1:算盘 2:鲍鱼 3:放弃 4:基础 5:羞愧 6:减弱 7:减法 8:继续输入
我稍后确实调用了析构函数,但这绝对是久经考验的话。
谁能建议如何修改它以便我可以存储字符串??
如果我是正确的,我还假设它是一个数组结构?
非常感谢
jack
最佳答案
char* wordArr[50];
您没有为您的单词分配任何内存。尝试:
int maxWordSize = 100;
char wordArr[50][maxWordSize];
关于c - 将递归函数中的几个字符串存储到 struct c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34658046/