First time here? Checkout the FAQ!
0 votes
#include <stdio.h>

int main(void)
    void *vp;
    char ch='g';
    char *cp="goofy";
    int j=20;
        printf("%c",*(char *)vp);
        printf("%d",*(int *)vp);
        printf("%c",(char *)vp+3);
    return 0;
asked in Programming by Active (1.1k points) 1 21 47 | 156 views

1 Answer

0 votes

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


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.

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.

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.9k points) 2 8 27

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
Top Users Oct 2017
  1. Arjun

    23338 Points

  2. Bikram

    17048 Points

  3. Habibkhan

    7912 Points

  4. srestha

    6228 Points

  5. Debashish Deka

    5438 Points

  6. jothee

    4968 Points

  7. Sachin Mittal 1

    4772 Points

  8. joshi_nitish

    4286 Points

  9. sushmita

    3964 Points

  10. Rishi yadav

    3794 Points

Recent Badges

Popular Question makhdoom ghaya
Popular Question junaid ahmad
Notable Question learner_geek
Notable Question jothee
Popular Question jothee
Notable Question Jeffrey Jose
Notable Question air1ankit
Nice Question jothee
Verified Human shaleen25
Popular Question jothee
27,290 questions
35,142 answers
33,231 users