Discussion
What is the output of this C code?
#include <stdio.h>
int main()
{
int i = 10;
void *p = &i;
printf("%d\n", (int)*p);
return 0;
}
Answer: A
Correct answer: Compile time error
void is an incomplete type, so *p on a void * has no type and no size and the compiler rejects it. The cast in (int)*p comes too late: the dereference must be resolved before anything can be cast.
The correct form casts the pointer first, as *(int *)p, telling the compiler how to read the memory before reading it. That is exactly what the companion question does with a float *, and it is why void * can carry any object pointer but can be dereferenced through none.
No comment is present. Be the first to comment.
Loading…
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development