C Quiz – 111 | Question 1

Pick the best statement for the following program snippet:

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <stdio.h>
  
int main()
{
 int var;  /*Suppose address of var is 2000 */
  
 void *ptr = &var;
 *ptr = 5;
 printf("var=%d and *ptr=%d",var,*ptr);
               
 return 0;
}

chevron_right


(A) It will print “var=5 and *ptr=2000”
(B) It will print “var=5 and *ptr=5”
(C) It will print “var=5 and *ptr=XYZ” where XYZ is some random address
(D) Compile error


Answer: (D)

Explanation: Key point in the above snippet is dereferencing of void pointer. It should be noted that dereferencing of void pointer isn’t allowed because void is an incomplete data type. The correct way to assign value of 5 would be first to typecast void pointer and then use it. So instead of *ptr, one should use *(int *)ptr. Correct answer is d.

Quiz of this Question



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.