2,257 views
0 votes
0 votes
#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;
}

3 Answers

0 votes
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.

Related questions

0 votes
0 votes
1 answer
1
2 votes
2 votes
1 answer
3
0 votes
0 votes
1 answer
4
Nishi Agarwal asked Mar 10, 2019
601 views
void f(int x,int &y,const int &z){x+=z; y+=z;}int main(){ int a=22,b=33,c=44; f(a,b,c); f(2*a-3,b,c); printf("a=%d b=%d c=%d",a,b,c); return 0;}