[英]How do I cast these void pointers?
Im doing exam review and one of the questions says there is something wrong with this code and im supposed to fix it. 我正在做考试复习,并且一个问题说此代码出了点问题,我应该修复它。 I know it has something to do with the void pointer but cant figure it out.
我知道它与void指针有关,但无法弄清楚。 Does anyone know what i would do?
有人知道我会做什么吗?
void whatAmI(void *vp, int n) {
if (n == 1) {
printf(“Integer: %d\n”, vp);
} else if (n == 2) {
printf(“Double: %.2fl\n”, vp);
} else {
printf(“Unknown type!”);
}
}
You need to dereference the pointer vp
to print the value stored at the location pointed by vp
. 您需要取消对指针
vp
引用,以打印存储在vp
指向的位置的值。 But a void
pointer can't be dereferenced (doing so invokes undefined behavior ), so you need to cast it: 但是不能取消引用
void
指针(这样做会调用未定义的行为 ),因此您需要进行强制转换:
void whatAmI(void *vp, int n) {
if (n == 1) {
printf("Integer: %d\n", *(int *)vp);
} else if (n == 2) {
printf("Double: %.2fl\n", *(double *)vp);
} else {
printf("Unknown type!");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.