GATE CSE
First time here? Checkout the FAQ!
x
0 votes
121 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 (927 points)   | 121 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 Aug 2017
  1. ABKUNDAN

    4670 Points

  2. Bikram

    4556 Points

  3. akash.dinkar12

    3420 Points

  4. rahul sharma 5

    3124 Points

  5. manu00x

    2864 Points

  6. makhdoom ghaya

    2450 Points

  7. just_bhavana

    2136 Points

  8. Tesla!

    2042 Points

  9. stblue

    1930 Points

  10. joshi_nitish

    1686 Points


24,970 questions
32,072 answers
74,567 comments
30,150 users