简体   繁体   中英

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. 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 . But a void pointer can't be dereferenced (doing so invokes undefined behavior ), so you need to cast it:

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!");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM