好吧,我正在试着这样做,但它不工作,因为我没有取消引用指针…有没有一种方法可以在不为类型创建switch语句的情况下做到这一点?
typedef struct
{
char *ascii_fmtstr;
int len;
int (*deserializer)(void *in, const char *ascii);
int (*serializer)(const void *in, char *ascii);
} FORMAT;
const FORMAT formats[]=
{
{"%d\n", 2/2} //Int
,{"%s\n", STRSIZE/2} //String
,{"%.4f\n", 4/2} //Float
,{"%lld", 4/2} //Long-Long
,{"%s\n", STRSIZE/2} //Time
};
typedef struct {
int fmtindex;
void * vp;
} JUNK;
float f = 5.0f;
int i=1;
char foo[]="bar";
JUNK j[] = {
{2, &f}
,{0, &i}
,{1, foo}};
void dump(void)
{
int i;
for(i=0;i<2;i++)
printf(formats[j[i].fmtindex].ascii_fmtstr, j[i].vp);
}发布于 2013-04-26 14:33:12
看起来你是在把void *当作廉价的union来使用。这可不是个好主意。我想你会发现unions与enums和switches结合在一起,在C中使这看起来更整洁。你会在#ifdef SWITCH中找到switch ... #else,在#else中找到无开关版本... #endif。
#include <stdio.h>
struct object {
enum type {
d=0,
s=1,
f=2,
lld=3,
time=4
} type;
union instance {
int d;
char *s;
float f;
long long lld;
char *time;
} instance;
};
#ifdef SWITCH
void print_object(struct object *o) {
switch (o->type) {
case d: printf("%d", o->instance.d); break;
case s: printf("%s", o->instance.s); break;
case f: printf("%f", o->instance.f); break;
case lld: printf("%lld", o->instance.lld); break;
case time: printf("%s", o->instance.time); break;
};
}
#else
void print_d(struct object *o);
void print_s(struct object *o);
void print_f(struct object *o);
void print_lld(struct object *o);
void print_time(struct object *o);
void print_object(struct object *o) {
void (*print_functions[])(struct object *) = {
[d] = print_d,
[s] = print_s,
[f] = print_f,
[lld] = print_lld,
[time] = print_time
};
print_functions[o->type](o);
}
void print_d(struct object *o) { printf("%d", o->instance.d); }
void print_s(struct object *o) { printf("%s", o->instance.s); }
void print_f(struct object *o) { printf("%f", o->instance.f); }
void print_lld(struct object *o) { printf("%lld", o->instance.lld); }
void print_time(struct object *o) { printf("%s", o->instance.time); }
#endif
int main(void) {
struct object o = { .type = d, /* type: int */
.instance = { .d = 42 } /* value: 42 */ };
print_object(&o);
return 0;
}发布于 2013-04-26 13:38:21
您可以使用类似%p的内容来打印指针本身,但是,如果您想要打印指针所指向的内容,则需要告诉它是什么:
printf ("%d", *((int*)myVoidPtr));不允许取消引用void *,因为编译器不知道它指向的是什么。
发布于 2013-04-26 13:51:36
这样想:Any指针简单地指向single memory location.But,指针的type确定在那之后要解释/考虑的how many字节。如果它是char*,那么(取决于系统)1字节被解释,如果它是int*,4字节被解释,所以void*有了no type,.So,你不能在C中取消引用void指针,因为这个简单的reason.But,你可以打印出它指向的地址,在printf()中使用%p格式说明符,并将void指针作为参数传递。
printf("The address pointed by void pointer is %p",void_ptr); //Correct
printf("The address pointed by void pointer is %p",(void*)int_ptr);//Correct假设int_ptr是一个整数指针,而void_ptr是一个空指针。
printf("Value at address pointed by void pointer is %d",*void_ptr);// Wrong
printf("Value at address pointed by void pointer is %d",*(void*)int_ptr);//Wronghttps://stackoverflow.com/questions/16229417
复制相似问题