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

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?

Choose one option.
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:

  1. Original code has void *ptr; at line 5 (actually line 6 counting the includes).
  2. At line 8, printf("%d", *ptr) tries to dereference a void pointer.
  3. Problem: void* is a generic pointer with no type information. Dereferencing it directly is undefined behavior and causes compiler errors.
  4. Solution: Declare ptr with a concrete type matching what it will point to.
  5. Since mz is an int, change void *ptr to int *ptr.
  6. Now *ptr correctly retrieves the integer value.
  7. 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 type void).
  • Option C: Changing printf to printf("%d", &mz) avoids dereferencing but doesn't fix the fundamental type mismatch with void*; the original issue persists.