C Programming - Pointers - Discussion

Discussion Forum : Pointers - Find Output of Program (Q.No. 10)
10.
What will be the output of the program ?
#include<stdio.h>

int main()
{
    void *vp;
    char ch=74, *cp="JACK";
    int j=65;
    vp=&ch;
    printf("%c", *(char*)vp);
    vp=&j;
    printf("%c", *(int*)vp);
    vp=cp;
    printf("%s", (char*)vp+2);
    return 0;
}
JCK
J65K
JAK
JACK
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
84 comments Page 5 of 9.

Surekha said:   7 years ago
Nice explanation, Thanks @Nilesh.

Prajakta said:   7 years ago
Thanks @Nilesh.

Nikhil navgire said:   8 years ago
Thanks @Nilesh well explained!

Bijan said:   1 decade ago
Hi sourav,
Typecasting is making a variable of one type, such as an int, act like another type, a char, for one single operation. To typecast something, simply put the type of variable you want the actual variable to act as inside parentheses in front of the actual variable. (char)a will make 'a' function as a char.

#include <iostream>

using namespace std;

int main()
{
cout<< (char)65 <<"\n";
// The (char) is a typecast, telling the computer to interpret the 65 as a
// character, not as a number. It is going to give the character output of
// the equivalent of the number 65 (It should be the letter A for ASCII).
cin.get();
}

Chitra said:   1 decade ago
ch=74 which is the ASCII value of J
j=65 which is the ASCII value of A
vp a void pointer contains the address of ch so it can be type casted to any type of pointer.
printf("%c", *(char*)vp);
(char*)vp type castes void type vp to char type and prints the value pointed by vp which is J.
vp=&j;
printf("%c", *(int*)vp);
Now vp contains the address of j.
*(int*)vp it type castes void type pointer vp to int type and prints the value pointed by vp which is A
vp=cp;
printf("%s", (char*)vp+2);
Now vp contains the value of cp. pointer vp is incremented by 2.so now it points to the letter C of JACK and prints the string CK.

So finally JACK is printed.

Kavya said:   1 decade ago
Thanks Nilesh, nice explanation.

Zohra said:   1 decade ago
Thanks Nilesh. Well explained.

Divya said:   1 decade ago
q = (int**)&p;
Here void ptr is casted into integer ptr.

this was d explantion given for typecasting in 1 of the discussion...

*(char*)vp-dis is also typecasting.. but both differs..

Pragnya said:   1 decade ago
For @Lucky:

ch is a character variable. From the character set, we can assign any kind of values to the character variable. The character set consists of floating point no. s, integers, characters, special characters etc. which when given charater datatype behave as character.

Divya said:   1 decade ago
Thank you very much Nilesh.


Post your comments here:

Your comments will be displayed after verification.