我正在制作一个变位词程序,它接受一个单词并找到它的变位词,然后从给定的字典文件中返回变位词列表。我使用链表作为散列映射和散列映射的每个节点的列表(根据我的分配)。我是 C 的新手,所以我在内存和指针方面遇到了很多问题。
我在编译时遇到的一些常见错误: 警告:初始化使指针来自整数而不进行强制转换 列表 *pList = getListFromMap(key); 我不明白这个,pList 是一个列表指针,而 getListFromMap 返回的是一个列表指针。
getListFromMap() 的冲突类型 列表 *getListFromMap(int key) {
之前的 getListFromMap 声明在这里 getListFromMap(键); 我读了一些关于前向声明的内容?虽然我不确定这是如何工作的,但我在尝试时遇到了错误。
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);
}
最佳答案
尽管函数返回指针,但您收到“初始化从整数生成指针”警告的原因有些模糊。根本原因是函数没有原型(prototype),但这不是全部。根据 C99 之前的规则,您可以调用没有前向声明的函数,但编译器必须假定所有参数都受制于 default type promotions。 ,返回类型也是int
。
这就是为什么当编译器看到 pListHead = getListFromMap(key)
调用时,它假定该函数返回一个 int
。为了避免这个问题,在文件顶部添加一个前向声明,紧跟在 typedef
之后:
list *getListFromMap(int key);
关于c - 当函数返回指针时,为什么我得到 "initialization makes pointer from integer"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38295618/