GATE CSE
First time here? Checkout the FAQ!
x
0 votes
46 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 (793 points)   | 46 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)  

Related questions

+5 votes
1 answer
1
asked in Programming by Mandeep Singh Active (1.1k points)   | 190 views
+1 vote
2 answers
2
asked in Programming by gaurav9822 (497 points)   | 132 views
+2 votes
1 answer
3
asked in Programming by gaurav9822 (497 points)   | 95 views
Members at the site
Top Users Feb 2017
  1. Arjun

    4676 Points

  2. Bikram

    4004 Points

  3. Habibkhan

    3738 Points

  4. Aboveallplayer

    2966 Points

  5. sriv_shubham

    2278 Points

  6. Smriti012

    2212 Points

  7. Arnabi

    1814 Points

  8. Debashish Deka

    1788 Points

  9. sh!va

    1444 Points

  10. mcjoshi

    1444 Points

Monthly Topper: Rs. 500 gift card

20,788 questions
25,938 answers
59,532 comments
21,923 users