The program given below gives a compiler error in line 7.
Qualcomm technical mcq question, verified with a worked answer. Free to practise - no sign-up.
The program given below gives a compiler error in line 7.
#include <stdio.h>
int main()
{
void *ptr;
int mz = 9;
ptr = &mz;
printf("%d", *ptr);
}
Which of the statement given in the option is the correct one to be replaced in the program so that it will be error free?
Show answer & explanation
Answer: B. Line 4 - int *ptr;
The error occurs at line 8 (printf) because *ptr dereferences a void* pointer, and the compiler cannot determine the size or type of data to retrieve. Changing void *ptr to int *ptr allows the compiler to know that ptr points to an int, so *ptr correctly dereferences it as an integer. Option A is invalid syntax; Option C still leaves the type mismatch unresolved.
Step-by-step Derivation:
Step-by-step analysis:
- Original code has
void *ptr;at line 5 (actually line 6 counting the includes). - At line 8,
printf("%d", *ptr)tries to dereference a void pointer. - Problem:
void*is a generic pointer with no type information. Dereferencing it directly is undefined behavior and causes compiler errors. - Solution: Declare
ptrwith a concrete type matching what it will point to. - Since
mzis anint, changevoid *ptrtoint *ptr. - Now
*ptrcorrectly retrieves the integer value. - Result:
printf("%d", *ptr)prints the value 9 without error.
Why other options fail:
- Option A:
void ptr;is invalid syntax (cannot declare a variable of typevoid). - Option C: Changing printf to
printf("%d", &mz)avoids dereferencing but doesn't fix the fundamental type mismatch withvoid*; the original issue persists.