826 views
4 votes
4 votes
#include<stdio.h>
int main()
{
    int a = 12;
    void *ptr = (int *)&a;
    printf("%d", *ptr);
    getchar();
    return 0;
}

A

12

B

Compiler Error

C

Runt Time Error

D

0

3 Answers

3 votes
3 votes

answer B 

 you will get this error 

Compiler Error: 'void*' is not a pointer-to-object type 

 because you have to typecast void pointer to int pointer.

you have to use 

print("%d",*(int *)ptr);

https://www.geeksforgeeks.org/void-pointer-c/

2 votes
2 votes
Answer is compiler error

Reason : printf("%d",*ptr), void * type cannot be de-referenced, we need do type casting before doing  it. If you want 12, then printf("%d",*(int *)ptr) should be written.
0 votes
0 votes
answer is B

As *ptr is void pointer we have to type cast it before printing *ptr.Actually what is going on is ptr is pointing to address of a,now we are printing value to which ptr is pointing .When it goes to address of a then as ptr is void pointer it does not know until which byte it print

i.e either 2B or 4B or 6B whatever.If we typecast   it into int then it will print upto next 2B starting from address of a or if we typecast it into char then it will print next one byte from address of a.

example let a=9  &a=1000 since int take 2B (16bit)  a=(00000000)(00001001) first eight bit(MSB) store at 1001 location and next at 1000 location (This is called Little Endian)

now if we typecast it into char i.e printf("%d",*(char *)ptr) then it will print only one bit from starting i.e 9

Related questions

0 votes
0 votes
2 answers
1
Debargha Mitra Roy asked Apr 16
122 views
#include <stdio.h int main() { int a[3] = {1, 3, 5, 7, 9, 11}; int *ptr = a[0]; ptr += sizeof(int); printf("%d", *ptr); return 0; }(Assume size of int to be $2$ bytes.)T...
0 votes
0 votes
2 answers
3
Debargha Mitra Roy asked Apr 10
145 views
What is the output of the below code?#include <stdio.h void main() { static int var = 5; printf("%d ", var ); if (var) main(); }a. 1 2 3 4 5b. 1c. 5 4 3 2 1d. Error
1 votes
1 votes
1 answer
4
SSR17 asked Feb 29
277 views
#include <stdio.h int main() { int i = -1; int x = (unsigned char)i; printf("%d", x); return 0; }output is 255 , but please explain how