c 函数指针解释
我找到了一些我需要用于我的应用程序的代码,但其中有两行,我无法弄清楚它们到底做了什么以及如何做...请向我解释它们或将我引导到一个链接,以便我可以阅读更多相关内容。
Dict* dcreate(hash_size size, hash_size (*hashfunc) (const char *));
这里我猜它正在传递一个函数作为参数,其参数位于下面的括号中!?
hash_size i = dict->hashfunc(key) % dict->size;
在这里,我的猜测和我的狗的一样好!
hashfunc
:
static hash_size def_hashfunc(const char* key){
hash_size s = 0;
while(*key){
s += (unsigned char) *key++;
}
return s;
}
谢谢。
I have found some code that I need to use for my application but there are two lines in it I can't figure out what exactly do they do and how... Please, either explain them to me or direct me to a link so I can read more about it.
Dict* dcreate(hash_size size, hash_size (*hashfunc) (const char *));
Here I guess it is passing a function as a parameter with it's parameter in the following bracket!?
hash_size i = dict->hashfunc(key) % dict->size;
and here, my guess is as good as my dog's!
The hashfunc
:
static hash_size def_hashfunc(const char* key){
hash_size s = 0;
while(*key){
s += (unsigned char) *key++;
}
return s;
}
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对于第一行,您的猜测是正确的。这是一个接受两个参数的函数的标头,其中一个是 hash_size 类型,另一个是指向参数为 const char* 的函数的指针> 并返回一个
hash_size
。在第二行中,
dict
似乎是一个指向结构体的指针,因此dict->hashfunc(key)
调用了函数hashfunc
,存储在 dict 结构中的指针。最后一部分 (... % dict->size
) 只是模运算。For the first line, your guess is correct. That is the header for a function that accepts two arguments, one of which is of the
hash_size
type, and another which is a pointer to a function whose argument is aconst char*
and returns ahash_size
.In the second line,
dict
appears to be a pointer to a struct, sodict->hashfunc(key)
calls the functionhashfunc
, a pointer to which is stored in thedict
struct. The last part (... % dict->size
) is just the modulo operation.是一个函数指针。
hashfunc
是一个指向函数的指针,该函数接收const char *
作为参数并返回hash_size
类型。Is a Function Pointer.
hashfunc
is a pointer to a function which receives aconst char *
as an argument and returns a typehash_size
.它仅传递函数指针作为参数。以下是应传递的函数类型的定义:
例如,接收
const char *
并返回hash_size
的函数。It only passes a function pointer as a parameter. The following is the definition of the function type that should be passed:
E.g. a function that receives a
const char *
and returnshash_size
.它是一个函数指针,
因此 dcreate() 将分配一个 Dict 并填充其字段 hashfunc,如下所示:
然后你可以调用 dict->hasfunc(const char *),它将返回 hash_size。
确实是:
It is a function pointer
So that dcreate() will allocate an Dict and fill its field hashfunc like:
Then you may call dict->hasfunc(const char *), it will return hash_size.
It is indeed: