【发布时间】:2016-07-10 19:15:36
【问题描述】:
我正在制作一个字谜程序,它接受一个单词并找到它的字谜,然后从给定的字典文件中返回字谜列表。我使用链表作为散列图和散列图每个节点的列表(根据我的分配)。我对 C 很陌生,所以我在内存和指针方面遇到了很多问题。
我在编译时遇到的一些常见错误: 警告:初始化使指针从整数而不进行强制转换 列表 *pList = getListFromMap(key); 这个我没看懂,pList是一个列表指针,getListFromMap是返回一个列表指针。
getListFromMap() 的冲突类型 列表 *getListFromMap(int key) {
getListFromMap 的先前声明在这里 getListFromMap(key); 我读了一些关于前向声明的东西?虽然我不确定它是如何工作的,但我尝试它时遇到了错误。
typedef struct list {
char *word;
struct list *next;
} list;
typedef struct hashmap {
list *words;
int key;
struct hashmap *next;
} hashmap;
hashmap *pMapHead;
hashmap *pMapCurr;
list *pListHead;
list *pListCurrd;
int sum = 0; // sum of words
int hCount = 0;
void addWordsToMap(int key, list *words) { // create hashmap
hashmap *pHash = pMapHead;
pMapCurr = pHash;
while (pMapCurr) {
pMapCurr = pMapCurr->next;
}
pMapCurr->words = words;
pMapCurr->key = key;
pMapCurr->next = NULL;
hCount += 1;
}
list *addWord(int key) {
pListHead = getListFromMap(key);
pListCurr = pListHead;
while (pListCurr) {
pListCurr = pListCurr->next;
}
pList->word = word;
pList->next = NULL;
pCurr->next = pList;
pCurr = pList;
return pListHead;
}
list *getListFromMap(int key) {
hashmap *map = pMapHead;
pMapCurr = map;
while (pMapCurr != NULL) {
if (pMapCurr->key == key) {
return pMapCurr->words;
free(map);
}
pMapCurr = pMapCurr->next;
}
}
int getSum(char* word) {
int sum = 0;
int i = 0;
while (word[i]) {
word[i] = toupper(word[i]);
sum += word[i] - '@';
i++;
}
return sum;
}
void loadWords() {
FILE* dict = fopen("/home/akw54/Desktop/CS283/akw54-cs283- summer2016/A1/dict", "r");
if (dict == NULL) {
return;
}
pListHead = (list *) malloc(sizeof(pListHead));
pListCurr = pListHead;
pMapHead = (hashmap *) malloc(sizeof(pMapHead));
pMapCurr = pMapHead;
int key = 0;
list wordList;
char word[128];
while(fgets(word, sizeof(word), dict) != NULL) {
key = getSum(word);
addWordsToMap(key, addWord(key));
}
free(dict);
}
void main() {
loadWords();
free(pMapHead);
free(pMapCurr);
free(pListHead);
free(pListCurr);
}
【问题讨论】:
-
对于初学者,请确保在代码中使用任何函数之前至少有一个函数原型出现。
-
在 getListFromMap 返回后对 free() 的调用永远不会执行,这可能是件好事。它并不总是返回某些东西这一事实并不是一件好事。
-
这个问题can be seen here的许多、许多次出现之一。
标签: c