C | Pointer Basics | Question 14

Predict the output of following program

filter_none

edit
close

play_arrow

link
brightness_4
code

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

(A) 12
(B) Compiler Error
(C) Runt Time Error
(D) 0

Answer: (B)
Explanation: There is compiler error in line “printf(“%d”, *ptr);”.

void * type pointers cannot be de-referenced. We must type cast them before de-referencing.

The following program works fine and prints 12.

#include<stdio.h>

int main()
{
    int a = 12;
    void *ptr = (int *)&a;
    printf("%d", *(int *)ptr);
    getchar();
    return 0;
}

Quiz of this Question

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

Article Tags :
C
Practice Tags :