gpt4 book ai didi

我可以将结构传递给采用 void* 的函数吗?

转载 作者:太空狗 更新时间:2023-10-29 17:20:47 25 4
gpt4 key购买 nike

因为这是一个 void* 我应该能够传递任何类型的指针,对吗?为什么编译器给我错误?

int cmp_func(void *, void *));

typedef struct word_{
char key[WORD_SIZE];
int *frequency;
} word;

Phash_table new_hash(int size, int (*hash_func)(char *), int (*cmp_func)(void *\
, void *));

int comp_function(struct word_ *word1,struct word_ *word2){
if( word1->frequency < word2->frequency){
return -1;
}
if(word1->frequency < word2->frequency){
return 1;
}
if(word1->frequency == word2->frequency){
return 0;
}
}


project4_functions.c:47:3: warning: passing argument 3 of 'new_hash' from incompatible pointer type [enabled by default]
hash.h:38:13: note: expected 'int (*)(void *, void *)' but argument is of type 'int (*)(struct word_ *, struct word_ *)'

最佳答案

关键是让你的比较函数也接受空指针:

int comp_function(void *a, void *b){
struct word *word1 = a;
struct word *word2 = b;
// Use word1 and word2 as before.
}

附录,关于为什么编译器给你警告:

引用我找到的c99标准here

A pointer to void may be converted to or from a pointer to any incomplete or object type. A pointer to any incomplete or object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

这意味着您可以使用如下代码,并且编译器不会发出您所看到的警告:

void *a = NULL;
int (*f)(int a, char *b) = NULL;
a = f;
f = a;

很容易推断这意味着以下内容也将起作用(毕竟,我们只是将“void*”替换为“struct foo*”,对吧?)

int (*f1)(void*, void*);
int (*f2)(struct foo*, struct foo*);
f1 = f2;

但是,这会生成您的警告,因为它尝试将指针类型分配给指向 void 的指针(反之亦然),这是标准所允许的。相反,它试图将 int (*)(struct foo*, struct foo*) 类型的值分配给 int (*)(void*, void*).

当然,您可以尝试让编译器对显式强制转换感到满意,这让编译器相信您必须知道自己在做什么。但在这样做时,即使在调用“不确定”行为时,您也会失去获得这些警告的特权和安全性。

关于我可以将结构传递给采用 void* 的函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10473531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com