GATE CSE
First time here? Checkout the FAQ!
x
0 votes
72 views
#include <stdio.h>

int main(void)
{
    void *vp;
    char ch='g';
    char *cp="goofy";
    int j=20;
    vp=&ch;
        printf("%c",*(char *)vp);
    vp=&j;
        printf("%d",*(int *)vp);
    vp=cp;
        printf("%c",(char *)vp+3);
    return 0;
}
asked in Programming by Junior (877 points)   | 72 views

1 Answer

0 votes

Speciality of void pointer is it can hold address of any type and can be typcasted to any type.

 vp=&ch;

This makes vp holding the address of ch.

 printf("%c",*(char *)vp); //outputs 'g'

Here first we type case vp to char pointer and is then dereferenced so it prints "character stored in ch character" i.e g.

vp=&j;
printf("%d",*(int *)vp);//outputs 20

Here also first we make vp point to address of int 'j'. Then in printf statement we first typecase vp to int pointer and then dereference it which results in printing the value stored in j i.e 20.

vp=cp;  
printf("%u",(char *)vp+3); // new printf added and it outputs address of 'f' in "goofy"
printf("%c",*((char *)vp+3)); //outputs 'f'

Here first we make vp point to cp. In 2nd printf we first type cast vp to char pointer and then adds 3 which results in printing the address of 'f' in "goofy". If we still have a doubt whether it really points to f or not, we can see in next printf.

answered by Loyal (3.5k points)  


Top Users Apr 2017
  1. akash.dinkar12

    3508 Points

  2. Divya Bharti

    2542 Points

  3. Deepthi_ts

    2040 Points

  4. rude

    1966 Points

  5. Tesla!

    1768 Points

  6. Shubham Sharma 2

    1610 Points

  7. Debashish Deka

    1588 Points

  8. Arunav Khare

    1454 Points

  9. Kapil

    1424 Points

  10. Arjun

    1420 Points

Monthly Topper: Rs. 500 gift card

22,076 questions
28,040 answers
63,230 comments
24,135 users