#include<stdio.h>
#include<stdlib.h>
void function(void *i, void *j);
struct mystruct {
int a;
int b;
} ;
int main()
{
int a = 50;
struct mystruct s ;
s.a = 100;
s.b = 200;
function(&a, &s);
}
void function(void *i, void *j)
{
printf("Integer is %d\n", *i);
printf("Struct member 1 is %d\n", j->a);
printf("Struct member 2 is %d\n", j->b);
}
我上面的代码。在编译时,我得到以下错误,我明白我需要做些什么来修复它们。
voidstartest.c: In function function:
voidstartest.c:27: warning: dereferencing void * pointer
voidstartest.c:27: error: invalid use of void expression
voidstartest.c:28: warning: dereferencing void * pointer
voidstartest.c:28: error: request for member a in something not a structure or union
voidstartest.c:29: warning: dereferencing void * pointer
voidstartest.c:29: error: request for member b in something not a structure or union
这是我需要做的来修复错误:
printf("Integer is %d\n", *(int*)i);
printf("Struct member 1 is %d\n", ((struct mystruct *)j)->a);
printf("Struct member 2 is %d\n", ((struct mystruct *)j)->b);
问题:
如果我必须按照上面描述的方式修复错误,这是否意味着我必须提前知道要发送给函数的指针类型?我觉得这是一个非常严格的要求。不是吗?
一些库函数也有作为 void * 的形式参数(如 qsort)。他们的实现如何知道指针的正确类型是什么,以便他们可以取消引用它以处理实际数据(它指向)?