0

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!”);
    }
}
Santa
  • 11,381
  • 8
  • 51
  • 64

1 Answers1

6

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!");
}
haccks
  • 104,019
  • 25
  • 176
  • 264
  • What about strict aliasing rules? Won't dereferencing `(int*)vp` and `(float*)vp` break them here? – Daniel Kamil Kozar Jun 26 '14 at 21:59
  • 1
    @DanielKamilKozar; *Aliasing refers to the situation where the same memory location can be accessed using different names.* But here memory is referenced using same name `vp` :) – haccks Jun 26 '14 at 22:05
  • @haccks : Thanks. I always get nervous when I see `*(int*)something` in the code. – Daniel Kamil Kozar Jun 26 '14 at 22:07
  • 1
    @DanielKamilKozar; Haven't you tried `qsort` and its `compare` function ? You should try that and then you will know more abot generic pointer `void *`. By the way you can read more about [Strict aliasing](http://stackoverflow.com/a/99010/2455888) here. – haccks Jun 26 '14 at 22:11
  • 2
    The `"Double: %.2fl\n"` suggests the pointer points to a `double` object and in that case you have to use `*(double *) vp`. – ouah Jun 26 '14 at 22:19
  • @ouah; Yes. I missed that. Its late night here. Too tired now. – haccks Jun 26 '14 at 22:21