OA. free
Free
Qualcomm Embedded Systems & Hardware Embedded Systems & Hardware Medium

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?

Choose one option.
Show answer & explanation
Answer: B. Line 4 - int *ptr;

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:

  1. Current code issue: Line 7 attempts printf("%d", *ptr) where ptr is void *.
  2. 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.
  3. Why option B works: Declaring int *ptr instead makes ptr a typed pointer to int. Now *ptr correctly dereferences to an int value, matching printf("%d", ...).
  4. Why others fail:
    • A: void ptr; is a syntax error; void cannot be a variable type.
    • C: printf("%d", &m2) passes the address (pointer), not the value; %d expects an int, not an int *.
    • D: printf("%d", ptr) passes the pointer value itself, not the dereferenced integer; type mismatch.
  5. Verification: With int *ptr; ptr = &m2; and printf("%d", *ptr);, the dereferenced pointer yields the integer 5, and the program compiles and runs correctly.