我有一个结构,其中包含一个函数变量,我想为其分配一个函数,它本身在全局级别上是可见的,如下所示:
typedef struct HashMap{
struct LinkedList** datapointers;
int key_space;
int* (*hash_function)(const char*);
}HashMap;
unsigned int hashfunction(const char* input){
int i=0;
int hash=0;
while(input[i]){
hash=hash+input[i];
i++;
}
return hash;
}
//create a new hashmap
HashMap* create_hashmap(int key_space){
HashMap *hm = malloc (sizeof(HashMap));
hm->datapointers = malloc(sizeof(LinkedList)*key_space); //array of linked lists
hm->key_space=key_space;
for(int i=0;i<key_space;i++){ //initalize to NULL
hm->datapointers[i]=NULL;
}
hm->hash_function=*hashfunction;
return hm;
}
现在无论我做什么,我都会收到无效指针或未声明的变量。有什么办法可以让它正常工作吗?
谢谢
最佳答案
你的代码应该是这样的
hm->hash_function = hashfunction;
但是,有一个不匹配。
函数指针类型为int* (*hash_function)(const char*);
但是你的函数签名是
unsigned int hashfunction(const char* input)
海事组织,应该是
int* hashfunction(const char* input)
[需要相应修改函数定义]
或
unsigned int (*hash_function)(const char*);
关于c 将外部函数函数分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27188584/