LearnFrenzy
Sign in Take a free test

Pointers · Find the Error · Question 5

Error: dereferencing a void pointer in C Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

The program below has a problem. Which statement correctly describes it?

main.c
#include <stdio.h>

int main(void) {
    int x = 5;
    void *vp = &x;
    printf("%d\n", *vp);
    return 0;
}
  • A void *vp = &x; – an int address cannot be stored in a void pointer
  • B *vp – a void pointer must be converted, e.g. *(int *) vp, before it is dereferenced Correct
  • C There is no error; it prints 5
  • D %d should be %v
Correct Answer: Option B

Storing any object address in a void * is fine. But the compiler does not know what type lives there, so *vp is not allowed. Write *(int *) vp.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Popular