QUESTION 30 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.
QUESTION 30
The program given below gives a compiler error in line 7.
#include <stdio.h>
int main()
{
void *ptr; //line 4
int m2 = 5; //line 5
ptr = &m2; //line 6
printf("%d", *ptr); //line 7
}
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
The issue is that *ptr dereferences a void * pointer, but printf("%d", ...) expects an int value, not a dereferenced void *. A void * pointer cannot be dereferenced without an explicit cast or type information. Changing line 4 to int *ptr; makes ptr a typed pointer to an integer, so *ptr correctly evaluates to an int value that printf can accept. Options A, C, and D do not fix the fundamental type mismatch: A removes the pointer entirely (syntax error), C passes the address instead of the value (type mismatch), and D passes the pointer itself instead of the dereferenced value (type mismatch).
Step-by-step Derivation:
Step-by-step analysis:
- Current code issue: Line 7 attempts
printf("%d", *ptr)whereptrisvoid *. - The problem:
void *is a generic pointer with no type information. Dereferencing it (*ptr) without a cast is undefined behavior—the compiler doesn't know what type to extract. - Why option B works: Declaring
int *ptrinstead makesptra typed pointer toint. Now*ptrcorrectly dereferences to anintvalue, matchingprintf("%d", ...). - Why others fail:
- A:
void ptr;is a syntax error;voidcannot be a variable type. - C:
printf("%d", &m2)passes the address (pointer), not the value;%dexpects anint, not anint *. - D:
printf("%d", ptr)passes the pointer value itself, not the dereferenced integer; type mismatch.
- A:
- Verification: With
int *ptr; ptr = &m2;andprintf("%d", *ptr);, the dereferenced pointer yields the integer5, and the program compiles and runs correctly.