GATE CSE
First time here? Checkout the FAQ!
x
0 votes
87 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 (907 points)   | 87 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 Jun 2017
  1. Bikram

    3704 Points

  2. Hemant Parihar

    1502 Points

  3. junaid ahmad

    1432 Points

  4. Arnab Bhadra

    1416 Points

  5. Niraj Singh 2

    1391 Points

  6. Debashish Deka

    1246 Points

  7. Rupendra Choudhary

    1194 Points

  8. rahul sharma 5

    1158 Points

  9. Arjun

    956 Points

  10. srestha

    950 Points

Monthly Topper: Rs. 500 gift card
Top Users 2017 Jun 19 - 25
  1. Bikram

    1960 Points

  2. Niraj Singh 2

    1386 Points

  3. junaid ahmad

    502 Points

  4. Debashish Deka

    414 Points

  5. sudsho

    410 Points


23,373 questions
30,079 answers
67,406 comments
28,396 users