我实现了一个队列,并且想要一个可以打印其元素的函数,而与类型无关。所以我做了一个函数printQueue,如下所示:
void printQueue(queue_t *queue, void (*f)(void *)) {
node_t *node = (*queue).front;
while(node != NULL) {
(*f)(node->item);
puts("");
node = (*node).next;
}
}
这个想法是它将接收队列,以及一个从队列中打印元素的功能(实现队列是为了能够容纳任何类型的元素)。因此,此函数将迭代队列并调用该函数以打印其每个元素。
然后,我制作了一个函数来打印int数组,这些数组在其第一个元素中包含自己的大小,如下所示:
void printSpecialIntArray(int *array) {
int i;
for(i=0; i<array[0]; i++) {
printf("%d ", array[i]);
}
}
但是,如果我Q
使用这种数组初始化队列并printQueue(Q, printSpecialIntArray)
说它似乎按预期工作,但我得到警告:
warning: passing argument 2 of ‘printQueue’ from incompatible pointer type [-Wincompatible-pointer-types]
printQueue(Q, printSpecialIntArray);
^~~~~~~~~~~~
In file included from main.c:3:0:
queue.c:32:6: note: expected ‘void (*)(void *)’ but argument is of type ‘void (*)(int *)’
void printQueue(queue_t *queue, void (*f)(void *)) {
为什么会发生此警告?如何解决?有没有更清洁的方法可以做到这一点?
另外,如果您想知道,我正在使用一个具有其自身大小的数组作为元素,因为我正在实现一个流程模拟器,而这些“特殊int数组”实际上应该表示一个流程。如果您知道一种更清洁的方法,也欢迎在答复/评论中加入。
错误消息非常简单。该函数void printQueue(queue_t *queue, void (*f)(void *))
期望f
是指向一个函数的指针,该函数返回void
并仅使用一个参数,其类型应为void*
。该函数printSpecialIntArray
不能满足此要求,因为其参数为int*
。
一种解决方案是进行更改f
,以int*
使其代替参数void*
。另一个解决方案是重写printSpecialIntArray
:
void printSpecialIntArray(void *a) {
int *array = (int*) a;
int i;
for(i=0; i<array[0]; i++) {
printf("%d ", array[i]);
}
}
注意:
即使可以将void指针安全地提升为int指针,该函数f
仍需要是一个以void指针作为参数的函数。问题不是参数,而是函数声明本身。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句